简体   繁体   English

为什么我不能在 TS 中返回字符串文字类型

[英]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.

相关问题 得到一个未终止的字符串文字错误..我可以让它通过,但无法弄清楚为什么 - Getting an unterminated string literal error..I can make it pass, but can't figure out why 为什么 Javascript 不能从字符串文字中解析这个 JSON 数组? - Why can't Javascript parse this JSON array from a string literal? 为什么(function(){return this;})。call(&#39;string literal&#39;)返回[String:&#39;string literal&#39;]而不是&#39;string literal&#39;? - Why does (function() { return this; }).call('string literal') return [String: 'string literal'] instead of 'string literal'? 为什么我不能直接访问对象文字的属性? - Why can't I directly access a property of an object literal? 为什么在创建此 javascript object 文字时不能使用“this”? - Why can't I use 'this' when creating this javascript object literal? 为什么我不能在我的对象文字中访问this.property? - why can't I access this.property in my object literal? Javascript对象字面量:为什么我不能这样做? - Javascript object literal: why can't I do this? 遵循教程但无法弄清楚为什么我会收到此消息:“类型'() =&gt; WordArray'.ts(2339) 上不存在属性'子字符串'” - Following a tutorial but can't figure out why I'm getting this message: "Property 'substring' does not exist on type '() => WordArray'.ts(2339)" 为什么我不能从对象文字中引用对象文字? - Why can't I reference an object literal from inside an object literal? 为什么字符串文字在 JavaScript 中被视为原始类型? - Why is the string literal considered a primitive type in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM