首页 > 解决方案 > 强制转换为“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 都显示了MyInterfaceIntelliSense 建议的 3 个属性:

keyof cast - 智能感知建议

const myVar: keyof MyInterface = "Prop4";显然按预期工作并引发错误,但第一个示例既不引发错误,也不确保类型安全。

这种说法合法吗?如果是这样,它应该如何表现?如果不是,为什么要编译?

标签: visual-studiotypescriptvisual-studio-code

解决方案


您正在使用类型断言,根据定义,类型断言会覆盖编译器所知道的真实内容,因为开发人员认为是真实的。如果你告诉编译器它知道不是一个键的字符串是它的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");

游乐场链接


推荐阅读