首页 > 解决方案 > 如何为具有可选属性的类型赋值?

问题描述

这是我的类型:

export type Supply = {
    id: number;
    name: string;
    manufacturer?: string;
    model?: string;
}

这是我尝试分配给具有该类型的对象的方法:

return response['data']['supplies'].map((supply: ServerResponse.Supply) => {
    let s = {
        id: supply['supply_id'],
        name: supply['name'],
    }

    if ('manufacturer' in supply) {
        s.manufacturer = supply['manufacturer']
    }

    if ('model' in supply) {
        s.model = supply['model']
    }

    return s;
});

我收到 TypeScript 警告:

[ts] 类型'{ id: number; 上不存在属性'制造商';名称:字符串;}'。

[ts] 类型 '{ id: number; 上不存在属性 'model' 名称:字符串;}'

我的代码有什么问题?

标签: typescript

解决方案


只需添加类型信息:

let s: Supply = {
        id: supply['supply_id'],
        name: supply['name'],
}

否则 TS 将根据初始声明假定您的变量s具有自己的类型{id: number, name: string}


推荐阅读