代码之家  ›  专栏  ›  技术社区  ›  user1283776

如何为具有可选属性的类型赋值?

  •  0
  • user1283776  · 技术社区  · 7 年前

    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]属性“manufacturer”在类型{id:number; 名称:string;}。

    [ts]属性“model”在类型“{id: 数字名称:string;}'

    我的代码有什么问题?

    1 回复  |  直到 6 年前
        1
  •  3
  •   HaneTV    7 年前

    只需添加类型信息:

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

    否则TS将假定您的变量 s 有自己的类型 {id: number, name: string}

    推荐文章