在分配Object.assign

时间:2017-05-09 21:42:45

标签: typescript

我有以下界面;

interface ComponentInterface {
    pollution: number,
    funds: number
}

interface ConfigInterface {
    pollution?: number,
    funds?: number
}

然后我有一个基于接口创建对象的函数;

function create(oConfig: ConfigInterface = {}): ComponentInterface {
    // Merge the config with component defaults
    const oComponent: ComponentInterface = Object.assign({
        pollution: 0
    }, oConfig);

    // ...
}

我正在调用函数,没有任何参数,如;

create();

我不明白为什么我的编译器没有在这里抛出错误。 AFAIK我将 {pollution:0} 分配给期望ComponentInterface的变量。

1 个答案:

答案 0 :(得分:1)

编译器运行良好 It does complain说:

  

输入'{污染:数字; }& ConfigInterface'不可分配给   输入'ComponentInterface'。
  属性'fund'在类型'{中是可选的   污染:数量; }& ConfigInterface'但在类型中是必需的   'ComponentInterface'。

考虑到signature of the function

,您期望的是什么
interface ObjectConstructor {
    assign<T, U>(target: T, source: U): T & U;
    ...
}

T{ pollution: number; }UConfigInterface

此外,您还可以使用Partial而不是重新定义所有道具:

type ConfigInterface = Partial<ComponentInterface>;
相关问题