lifeiscontent
lifeiscontent

Reputation: 593

How to type function with generic and default argument in TypeScript

function foo<T extends 'hello' | 'goodbye' = 'hello'>(bar: T = 'hello'): void { }

hello seems to not be valid here, not sure why because it's a part of the extends clause. Can someone explain this and potentially provide a solution?

Upvotes: 1

Views: 45

Answers (1)

Nishant
Nishant

Reputation: 55866

Here is the thing:

function foo<T extends 'hello' | 'goodbye'>(bar: T = 'hello'): void { }

can be initiated with

foo<'goodbye'>()

But as per your definition of foo, the default value would be 'hello' which contradicts the statement foo<'goodbye'>() which only allows parameter to be 'goodbye'.

So, with that explanation, you can have the following as your solution:

function foo(bar: 'hello' | 'goodbye' = 'hello'): void { }

This works, but I don't think it serves any greater purpose

function foo<T extends 'hello' | 'goodbye'>(bar: T): void { }

TS Playground: https://tsplay.dev/WyOzgN

Upvotes: 2

Related Questions