visual-studio - 强制转换为“keyof T”是否可以工作或导致编译错误?
问题描述
考虑以下 TypeScript 示例:
interface MyInterface{
Prop1: string;
Prop2: number;
Prop3: string;
}
const myVar = "Prop4" as keyof MyInterface;
在 Visual Studio 2017 中运行此代码,Visual Studio Code 和 Playground 成功编译(TypeScript 2.9.2);未对字符串值进行类型检查,MyInterface
但 VS 和 VSC 都显示了MyInterface
IntelliSense 建议的 3 个属性:
const myVar: keyof MyInterface = "Prop4";
显然按预期工作并引发错误,但第一个示例既不引发错误,也不确保类型安全。
这种说法合法吗?如果是这样,它应该如何表现?如果不是,为什么要编译?
解决方案
您正在使用类型断言,根据定义,类型断言会覆盖编译器所知道的真实内容,因为开发人员认为是真实的。如果你告诉编译器它知道不是一个键的字符串是它的MyInterface
一个键,MyInterface
它会按照它的设计接受这个(尽管它会阻止你在不相关的类型之间断言,例如这将是一个错误:)let d = true as keyof MyInterface;
。
如果您希望将变量键入为接口的键,但仍检查分配给它的值是否有效,您可以像您一样显式指定类型。
您还可以使用辅助函数:
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");
推荐阅读
- python - 如何修复:“错误”:“预测失败:未知错误。” 在 scikit-learn 的自定义预测例程中?
- powershell - PowerShell:关闭标准输出句柄
- r - 根据将其他列与另一个数据框匹配的值填充数据框的缺失值,同时保留不匹配的值
- javascript - 使用电子伪造打包应用程序时出现问题“无法解析'./→'”
- reactjs - redux 工具包中的变异状态
- xml - 如何在 Powershell 中显示整个 XML 树?
- asp.net-core - 将外部样式表页面分配给 .core Web 应用程序中的剃须刀页面
- laravel - Laravel snappy 返回 Failed to load about:blank, with network status code 301 and http status code 0 - 协议“about”未知错误
- java - 这是解决这个“oneFiveSeven”递归问题的正确方法吗?(不希望有效率)
- c# - 如何在 ASP.NET Core 中注册此依赖项?