代码之家  ›  专栏  ›  技术社区  ›  Andrei V

强制转换为“keyof t”是为了工作还是导致编译错误?

  •  1
  • Andrei V  · 技术社区  · 7 年前

    请考虑以下类型脚本示例:

    接口myinterface{
    prop1:字符串;
    Prop2:数字;
    Prop3:字符串;
    }
    
    const myvar=“prop4”作为myInterface的键;
    

    在Visual Studio 2017中运行此代码,Visual Studio代码和操场中的代码成功编译(typescript 2.9.2);字符串值不是针对myinterface进行类型检查的but both vs and vsc show the 3 properties ofmyinterfaceas intellisense suggestions:。

    const myvar:keyof myinterface=“prop4”;expectly works as intended and throws an error but the first example neither throws an error,nor secures type safety.

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

    在Visual Studio 2017中运行此代码时,Visual Studio代码和操场中的代码成功编译(typescript 2.9.2);字符串值不是根据MyInterface但是vs和vsc都显示了我的接口作为IntelliSense建议:

    keyof cast - intellisense suggestions

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

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    7 年前

    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");
    

    Playground link

    推荐文章