考虑以下TypeScript示例:
interface MyInterface{
Prop1: string;
Prop2: number;
Prop3: string;
}
const myVar = "Prop4" as keyof MyInterface;在Visual Studio2017中运行此代码,Visual Studio code和在Playground中成功编译(TypeScript 2.9.2);字符串值没有针对MyInterface进行类型检查,但VS和VSC都将MyInterface的3个属性显示为IntelliSense建议:

const myVar: keyof MyInterface = "Prop4";显然按预期工作并抛出错误,但第一个示例既没有抛出错误,也没有确保类型安全。
这句话合法吗?如果是这样,它应该如何表现呢?如果不是,为什么要编译呢?
发布于 2018-07-31 21:31:04
您正在使用类型断言,根据定义,类型断言将使用开发人员确定为真的内容覆盖编译器知道为真的内容。如果你告诉编译器它知道不是MyInterface的键的字符串是MyInterface的键,它会按照设计接受这个(尽管它会阻止你在不相关的类型之间断言,例如这将是一个错误:let d = true as keyof MyInterface;)。
如果您希望将变量类型化为接口的键,但仍要检查分配给它的值是否有效,则可以按照已有的方式显式指定类型。
您还可以使用helper函数:
interface MyInterface {
Prop1: string;
Prop2: number;
Prop3: string;
}
function keyOf<T>(key: keyof T) {
return key;
}
const myVar = keyOf<MyInterface>("Prop4"); //Argument of type '"Prop4"' is not assignable to parameter of type '"Prop1" | "Prop2" | "Prop3"'.
const myVar2 = keyOf<MyInterface>("Prop3");("Prop3");">Playground link
https://stackoverflow.com/questions/51614485
复制相似问题