TypeScript 当属性中的字符串不可分配给字符串字面量时,改进诊断,

vdzxcuhz  于 2个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(49)

TypeScript版本: 3.1.0-dev.20180810
代码

interface IceCreamOptions {
    readonly cherry: "yes" | "no"
}
declare function iceCream(options: IceCreamOptions): void;
const options = { cherry: "yes" };
iceCream(options);

预期行为:

错误信息建议为 options 添加类型注解。这应该是可检测到的,因为失败属性的来源是一个 PropertyAssignment ,它在一个对象字面量中被赋值给一个变量。(如果没有变量赋值,我们仍然可以建议在 const 之前使用 ``"yes" as "yes" although that isn't as pretty.) Could also come with a codefix. Note that in JS the fix is slightly different: put /** @type {IceCreamOptions} /,或者使用/* @type {"yes"} */ ("yes")`。

实际行为:

错误信息显示 Type 'string' is not assignable to type '"yes" | "no"'. ,但没有关于如何修复的信息。

ltqd579y

ltqd579y1#

add "yes" as "yes" is soooooooooooooooooooooooo ugly
are there any other way to declare the string literal type?

3qpi33ja

3qpi33ja2#

#10195 上进行的 @Kingwl 讨论。

u1ehiz5o

u1ehiz5o3#

我打算改进这个,但是我发现诊断类型是 DiagnosticMessageDiagnosticMessageChain,没有位置信息,而且我不能简单地获取对象字面量中的不可分配属性。
作为问题,我想用 DiagnosticRelatedInformation 链替换 DiagnosticMessageChain 以解决 isRelatedTo 的问题,这样就可以保留位置信息了。
ping @RyanCavanaugh
我遗漏了什么吗?

相关问题