如何将值分配给具有可选性的类型?

问题描述 投票:0回答:1

这是我喜欢的类型:

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

我得到的打字稿警告:

[TS]属性“制造商”上不存在类型“{ID:号码;名称:字符串; }”。

[TS]属性“模式”上不类型“存在{ID:号码;名称:字符串; }”

什么是错我的代码?

typescript
1个回答
2
投票

只需添加类型信息:

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

否则TS假设你的变量s具有基于初始宣布了自己的类型{id: number, name: string}

© www.soinside.com 2019 - 2024. All rights reserved.