[英]Why can't I return a string literal type in TS
I don't understand the following error:我不明白以下错误:
type Prefix = 'Ms' | 'Mrs' | 'Mr'
const broken = <T extends Prefix>(prefix: T): T => {
// do something
return 'Ms';
// If I do `return 'Ms' as 'Ms'` then it works
}
const works = <T extends Prefix>(prefix: T): T => {
// do something
return p;
}
const alsoWorks = (): Prefix => {
// do something
return 'Ms';
}
The method broken
is giving me broken
的方法给了我
Type '"Ms"' is not assignable to type 'T'.类型“Ms”不可分配给类型“T”。 '"Ms"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Prefix'. '"Ms"' 可分配给类型为'T' 的约束,但可以使用约束'Prefix' 的不同子类型来实例化'T'。
Not sure why this method doesn't work, but the other two do?不知道为什么这种方法不起作用,但其他两种方法?
TypeScript is complaining that the following call will not work: TypeScript 抱怨以下调用不起作用:
const res: 'Mr' = broken<'Mr'>('Mr');
If T
is instantiated to something else than Ms
, your return 'Ms'
is violating the the return type T
.如果T
被实例化为Ms
以外的其他东西,则您的return 'Ms'
违反了返回类型T
。
I think you are looking for -我想你正在寻找 -
broken<Prefix>('Ms')
or或者
broken('Ms' as Prefix)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.