Specifying the return type based on optional parametersA Typed array of functionsHow do you specify that a class property is an integer?Are strongly-typed functions as parameters possible in TypeScript?Creating String Literal Type with constSpecify return type in TypeScript arrow functionTypeScript type inference on function type parameter based on its argument typeHow can I check that a string is a property a particular interface in TypeScriptTypescript type inference of return dict keys based on supplied parametersTypes of optional and default parameters in typescriptAbstract function return type in typescript

Amplitude of a crest and trough in a sound wave?

Ordinal analysis and proofs of consistency

Why is Na5 not played in this line of the French Defense, Advance Variation?

Electricity free spaceship

Why did Intel abandon unified CPU cache?

A word that means "blending into a community too much"

Should I put programming books I wrote a few years ago on my resume?

Is there a set of positive integers of density 1 which contains no infinite arithmetic progression?

How does the Around command at zero work?

Was Self-modifying-code possible just using BASIC?

How to safely destroy (a large quantity of) valid checks?

Generate basis elements of the Steenrod algebra

Separate SPI data

With Ubuntu 18.04, how can I have a hot corner that locks the computer?

Why does this query, missing a FROM clause, not error out?

How to publish items after pipeline is finished?

The usage of kelvin in formulas

Is it possible to have 2 different but equal size real number sets that have the same mean and standard deviation?

What is the polarity of this barrel plug with a double circle?

Can the removal of a duty-free sales trolley result in a measurable reduction in emissions?

A map of non-pathological topology?

Is it okay to have a sequel start immediately after the end of the first book?

bash vs. zsh: What are the practical differences?

Do people with slow metabolism tend to gain weight (fat) if they stop exercising?



Specifying the return type based on optional parameters


A Typed array of functionsHow do you specify that a class property is an integer?Are strongly-typed functions as parameters possible in TypeScript?Creating String Literal Type with constSpecify return type in TypeScript arrow functionTypeScript type inference on function type parameter based on its argument typeHow can I check that a string is a property a particular interface in TypeScriptTypescript type inference of return dict keys based on supplied parametersTypes of optional and default parameters in typescriptAbstract function return type in typescript






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















function f<T>(defaultValue?: T) return defaultValue; 

const definitelyUndefined = f<string>(); // type: string | undefined
const definitelyString = f<string>('foobar'); // type: string | undefined


Is it possible to define f() such that definitelyUndefined is implicitly undefined and definitelyString is implicitly string?



Background



My real world use case is a function I'm working with and want to improve. It is function f<T>(o: [key: string]: T , key: string, defaultValue?: T) and it returns key[o] if it exists, otherwise defaultValue. When I provide it a defaultValue, I'm guaranteed to get T back, but Typescript considers it T | undefined.










share|improve this question
























  • My first thought was adding function f<T>(defaultValue: T): T; as an overload definition, but it doesn't work.

    – Mark
    Mar 24 at 20:53

















1















function f<T>(defaultValue?: T) return defaultValue; 

const definitelyUndefined = f<string>(); // type: string | undefined
const definitelyString = f<string>('foobar'); // type: string | undefined


Is it possible to define f() such that definitelyUndefined is implicitly undefined and definitelyString is implicitly string?



Background



My real world use case is a function I'm working with and want to improve. It is function f<T>(o: [key: string]: T , key: string, defaultValue?: T) and it returns key[o] if it exists, otherwise defaultValue. When I provide it a defaultValue, I'm guaranteed to get T back, but Typescript considers it T | undefined.










share|improve this question
























  • My first thought was adding function f<T>(defaultValue: T): T; as an overload definition, but it doesn't work.

    – Mark
    Mar 24 at 20:53













1












1








1








function f<T>(defaultValue?: T) return defaultValue; 

const definitelyUndefined = f<string>(); // type: string | undefined
const definitelyString = f<string>('foobar'); // type: string | undefined


Is it possible to define f() such that definitelyUndefined is implicitly undefined and definitelyString is implicitly string?



Background



My real world use case is a function I'm working with and want to improve. It is function f<T>(o: [key: string]: T , key: string, defaultValue?: T) and it returns key[o] if it exists, otherwise defaultValue. When I provide it a defaultValue, I'm guaranteed to get T back, but Typescript considers it T | undefined.










share|improve this question
















function f<T>(defaultValue?: T) return defaultValue; 

const definitelyUndefined = f<string>(); // type: string | undefined
const definitelyString = f<string>('foobar'); // type: string | undefined


Is it possible to define f() such that definitelyUndefined is implicitly undefined and definitelyString is implicitly string?



Background



My real world use case is a function I'm working with and want to improve. It is function f<T>(o: [key: string]: T , key: string, defaultValue?: T) and it returns key[o] if it exists, otherwise defaultValue. When I provide it a defaultValue, I'm guaranteed to get T back, but Typescript considers it T | undefined.







typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 20:53







Mark

















asked Mar 24 at 20:44









MarkMark

456310




456310












  • My first thought was adding function f<T>(defaultValue: T): T; as an overload definition, but it doesn't work.

    – Mark
    Mar 24 at 20:53

















  • My first thought was adding function f<T>(defaultValue: T): T; as an overload definition, but it doesn't work.

    – Mark
    Mar 24 at 20:53
















My first thought was adding function f<T>(defaultValue: T): T; as an overload definition, but it doesn't work.

– Mark
Mar 24 at 20:53





My first thought was adding function f<T>(defaultValue: T): T; as an overload definition, but it doesn't work.

– Mark
Mar 24 at 20:53












1 Answer
1






active

oldest

votes


















3














For your first case, I immediately thought of using an overload, for example:



function f<T>(): undefined;
function f<T>(value: T): T;
function f<T>(value?: T) return value;

const definitelyUndefined = f(); // type: undefined
const definitelyString = f('foobar'); // type: "foobar"


However, for the more complex use case, I think perhaps you can solve it with overloads and more complex generics, for example:



function f<T, K extends string & keyof T>(o: T, key: K, defaultValue?: T[K]): T[K];
function f<T, V = undefined>(o: T, key: string, defaultValue?: V): V;
function f<T, V = undefined>(o: T, key: string, defaultValue?: V) defaultValue;


const obj = foo: "123" ;

const definitelyUndefined = f(obj, "bar"); // type: undefined
const definitelyNumber = f(obj, "bar", 123); // type: number
const definitelyString = f(obj, "foo"); // type: string


I don't know if this will work for every conceivable scenario (because the return type is determined based on the generic type argument, not the actual function argument), but I think it gets pretty close.






share|improve this answer

























  • It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

    – zerkms
    Mar 24 at 21:08







  • 1





    @zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

    – p.s.w.g
    Mar 24 at 21:11











  • This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

    – Mark
    Mar 24 at 21:15






  • 1





    @zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

    – p.s.w.g
    Mar 24 at 21:30











  • @p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

    – zerkms
    Mar 24 at 21:49











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328397%2fspecifying-the-return-type-based-on-optional-parameters%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














For your first case, I immediately thought of using an overload, for example:



function f<T>(): undefined;
function f<T>(value: T): T;
function f<T>(value?: T) return value;

const definitelyUndefined = f(); // type: undefined
const definitelyString = f('foobar'); // type: "foobar"


However, for the more complex use case, I think perhaps you can solve it with overloads and more complex generics, for example:



function f<T, K extends string & keyof T>(o: T, key: K, defaultValue?: T[K]): T[K];
function f<T, V = undefined>(o: T, key: string, defaultValue?: V): V;
function f<T, V = undefined>(o: T, key: string, defaultValue?: V) defaultValue;


const obj = foo: "123" ;

const definitelyUndefined = f(obj, "bar"); // type: undefined
const definitelyNumber = f(obj, "bar", 123); // type: number
const definitelyString = f(obj, "foo"); // type: string


I don't know if this will work for every conceivable scenario (because the return type is determined based on the generic type argument, not the actual function argument), but I think it gets pretty close.






share|improve this answer

























  • It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

    – zerkms
    Mar 24 at 21:08







  • 1





    @zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

    – p.s.w.g
    Mar 24 at 21:11











  • This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

    – Mark
    Mar 24 at 21:15






  • 1





    @zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

    – p.s.w.g
    Mar 24 at 21:30











  • @p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

    – zerkms
    Mar 24 at 21:49















3














For your first case, I immediately thought of using an overload, for example:



function f<T>(): undefined;
function f<T>(value: T): T;
function f<T>(value?: T) return value;

const definitelyUndefined = f(); // type: undefined
const definitelyString = f('foobar'); // type: "foobar"


However, for the more complex use case, I think perhaps you can solve it with overloads and more complex generics, for example:



function f<T, K extends string & keyof T>(o: T, key: K, defaultValue?: T[K]): T[K];
function f<T, V = undefined>(o: T, key: string, defaultValue?: V): V;
function f<T, V = undefined>(o: T, key: string, defaultValue?: V) defaultValue;


const obj = foo: "123" ;

const definitelyUndefined = f(obj, "bar"); // type: undefined
const definitelyNumber = f(obj, "bar", 123); // type: number
const definitelyString = f(obj, "foo"); // type: string


I don't know if this will work for every conceivable scenario (because the return type is determined based on the generic type argument, not the actual function argument), but I think it gets pretty close.






share|improve this answer

























  • It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

    – zerkms
    Mar 24 at 21:08







  • 1





    @zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

    – p.s.w.g
    Mar 24 at 21:11











  • This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

    – Mark
    Mar 24 at 21:15






  • 1





    @zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

    – p.s.w.g
    Mar 24 at 21:30











  • @p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

    – zerkms
    Mar 24 at 21:49













3












3








3







For your first case, I immediately thought of using an overload, for example:



function f<T>(): undefined;
function f<T>(value: T): T;
function f<T>(value?: T) return value;

const definitelyUndefined = f(); // type: undefined
const definitelyString = f('foobar'); // type: "foobar"


However, for the more complex use case, I think perhaps you can solve it with overloads and more complex generics, for example:



function f<T, K extends string & keyof T>(o: T, key: K, defaultValue?: T[K]): T[K];
function f<T, V = undefined>(o: T, key: string, defaultValue?: V): V;
function f<T, V = undefined>(o: T, key: string, defaultValue?: V) defaultValue;


const obj = foo: "123" ;

const definitelyUndefined = f(obj, "bar"); // type: undefined
const definitelyNumber = f(obj, "bar", 123); // type: number
const definitelyString = f(obj, "foo"); // type: string


I don't know if this will work for every conceivable scenario (because the return type is determined based on the generic type argument, not the actual function argument), but I think it gets pretty close.






share|improve this answer















For your first case, I immediately thought of using an overload, for example:



function f<T>(): undefined;
function f<T>(value: T): T;
function f<T>(value?: T) return value;

const definitelyUndefined = f(); // type: undefined
const definitelyString = f('foobar'); // type: "foobar"


However, for the more complex use case, I think perhaps you can solve it with overloads and more complex generics, for example:



function f<T, K extends string & keyof T>(o: T, key: K, defaultValue?: T[K]): T[K];
function f<T, V = undefined>(o: T, key: string, defaultValue?: V): V;
function f<T, V = undefined>(o: T, key: string, defaultValue?: V) defaultValue;


const obj = foo: "123" ;

const definitelyUndefined = f(obj, "bar"); // type: undefined
const definitelyNumber = f(obj, "bar", 123); // type: number
const definitelyString = f(obj, "foo"); // type: string


I don't know if this will work for every conceivable scenario (because the return type is determined based on the generic type argument, not the actual function argument), but I think it gets pretty close.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 24 at 21:28

























answered Mar 24 at 21:02









p.s.w.gp.s.w.g

122k19218260




122k19218260












  • It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

    – zerkms
    Mar 24 at 21:08







  • 1





    @zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

    – p.s.w.g
    Mar 24 at 21:11











  • This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

    – Mark
    Mar 24 at 21:15






  • 1





    @zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

    – p.s.w.g
    Mar 24 at 21:30











  • @p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

    – zerkms
    Mar 24 at 21:49

















  • It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

    – zerkms
    Mar 24 at 21:08







  • 1





    @zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

    – p.s.w.g
    Mar 24 at 21:11











  • This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

    – Mark
    Mar 24 at 21:15






  • 1





    @zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

    – p.s.w.g
    Mar 24 at 21:30











  • @p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

    – zerkms
    Mar 24 at 21:49
















It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

– zerkms
Mar 24 at 21:08






It's weird your "more complex" example does not run on typescriptlang.org/play UPD: it actually does not run in ts 3.3.3333 locally either.

– zerkms
Mar 24 at 21:08





1




1





@zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

– p.s.w.g
Mar 24 at 21:11





@zerkms I see the issue. Odd -- I didn't get the error earlier in the playground (maybe the parser was just a little slow). I'll see if I can correct it.

– p.s.w.g
Mar 24 at 21:11













This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

– Mark
Mar 24 at 21:15





This line (function f<T>(): undefined;) cleared it up for me. Without it TS was complaining that An argument for 'defaultValue' was not provided. Once I added that it worked like a charm. Your second example is great for me to learn from, but my actual use case has a few caveats I left out so I wouldn't be able to use it (see getFieldValue here).

– Mark
Mar 24 at 21:15




1




1





@zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

– p.s.w.g
Mar 24 at 21:30





@zerkms Updated, but I'm still not 100% happy with the provided solution. It still conflates 'type space' and 'value space' but I'm not sure if that can be avoided without more restrictions on T.

– p.s.w.g
Mar 24 at 21:30













@p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

– zerkms
Mar 24 at 21:49





@p.s.w.g it looks good to me - I was half-way writing a similar answer right when you posted it :-)

– zerkms
Mar 24 at 21:49



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328397%2fspecifying-the-return-type-based-on-optional-parameters%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해