【问题标题】:Typescript type inference on dynamically accessed object properties对动态访问的对象属性的打字稿类型推断
【发布时间】:2019-10-27 21:45:54
【问题描述】:
interface CustomResponse {
    data: string;
    status: number;
    [key: string]: string | number;
}

const RESPONSE_PROPS = {
  DATA: "data",
  STATUS: "status",
};

const response: CustomResponse = {
    data: "test",
    status: 200,
};

let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;

dataWrong 得到错误

Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'

在上述情况下,如何在 typescript 中获得dataWrong infer 正确的类型?类型断言(更好的类型保护)是唯一的方法吗?

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    如果您使用as const 断言(这将使编译器为RESPONSE_PROPS.DATA 保留字符串文字类型"data"),则RESPONSE_PROPS.DATA 的类型为string,它按预期工作:

    interface CustomResponse {
        data: string;
        status: number;
        // [key: string]: string | number; not necessary for the code to work
    }
    
    const RESPONSE_PROPS = {
        DATA: "data",
        STATUS: "status",
    } as const;
    
    const response: CustomResponse = {
        data: "test",
        status: 200,
    };
    
    let dataWrong: string = response[RESPONSE_PROPS.DATA];
    let dataRight: string = response.data;
    

    注意:如果使用字符串文字类型进行索引,则实际上不需要索引签名。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2018-09-19
    • 1970-01-01
    • 2021-07-02
    • 2023-02-26
    • 1970-01-01
    相关资源
    最近更新 更多