我有以下界面;
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的变量。
答案 0 :(得分:1)
编译器运行良好 It does complain说:
,您期望的是什么输入'{污染:数字; }& ConfigInterface'不可分配给 输入'ComponentInterface'。
属性'fund'在类型'{中是可选的 污染:数量; }& ConfigInterface'但在类型中是必需的 'ComponentInterface'。
interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
...
}
T
为{ pollution: number; }
且U
为ConfigInterface
。
此外,您还可以使用Partial
而不是重新定义所有道具:
type ConfigInterface = Partial<ComponentInterface>;