I cannot figure out why the following code confuses the compiler.
enum Enum {
a,
b,
c
}
const func = <T extends Enum>(param: T = Enum.a) => param;
Here I constrain T
to be of type Enum
and set the default parameter to be the enumerator Enum.a
. But TypeScript fails at the (param: T = Enum.a)
part with the message Type 'Enum.a' is not assignable to type 'T'.
What am I missing here, for I cannot figure it out on my own and the online resources I can find only cover the basics?
Here is a playground url
It's an error for the same reason as the following is an error:
class Bar {
bar = 123
}
const a = new Bar();
// Error `Bar` is not assignable to `T`
const bar = <T extends Bar>(param: T = a) => param;
Because T
might be something that extends Bar
and therefore Bar
would not be a compatible value.
class Baz extends Bar {
baz = 456;
}
const example:Baz = bar<Baz>(); // will blow up