I don’t understand the following error:
JavaScript
x
21
21
1
type Prefix = 'Ms' | 'Mrs' | 'Mr'
2
3
const broken = <T extends Prefix>(prefix: T): T => {
4
// do something
5
return 'Ms';
6
7
// If I do `return 'Ms' as 'Ms'` then it works
8
9
}
10
11
const works = <T extends Prefix>(prefix: T): T => {
12
// do something
13
return p;
14
}
15
16
const alsoWorks = (): Prefix => {
17
// do something
18
return 'Ms';
19
}
20
21
The method broken
is giving me
Type ‘”Ms”‘ is not assignable to type ‘T’. ‘”Ms”‘ is assignable to the constraint of type ‘T’, but ‘T’ could be instantiated with a different subtype of constraint ‘Prefix’.
Not sure why this method doesn’t work, but the other two do?
Advertisement
Answer
TypeScript is complaining that the following call will not work:
JavaScript
1
2
1
const res: 'Mr' = broken<'Mr'>('Mr');
2
If T
is instantiated to something else than Ms
, your return 'Ms'
is violating the the return type T
.