Home > Back-end >  How to make generics and default value work together
How to make generics and default value work together

Time:01-08

How can I modify this code to run

function say<T = boolean>(arg:T = false) {
//                        ^^^^^^^^^^^^^ Could be instantiated with an arbitrary type which could be unrelated to
    if(arg) return ['hello']
    return 'hello'
}

const a = say() //type is string
const b = say(true) //type is string[]

CodePudding user response:

You can use a conditional return type with assertions, like this:

TS Playground

function say <T extends boolean = false>(value = false as T) {
  return (value ? ['hello'] : 'hello') as T extends true ? string[] : string;
}

Or an overloaded function signature, like this:

TS Playground

function say (value?: false): string;
function say (value: true): string[];
function say (value = false) {
  return (value ? ['hello'] : 'hello') as unknown;
}

In both cases, calling the function with false or implicit undefined will result in string, and calling with true will result in string[]:

say(); // string
say(false); // string
say(true); // string[]
  •  Tags:  
  • Related