Reputation: 593
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
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