在合并对象上设置属性的优先级

时间:2018-07-12 07:58:22

标签: typescript ecmascript-6 merge configuration object-destructuring

在打字稿中,我发现您可以执行以下操作:

// Configuration interface, all properties are optional, the user can specify them but does not need to
interface IConfig {
    foo?: string;
    bar?: string;
}

// properties which are not specified by the user should take their default value defined here
let defaultConfig: IConfig = {
    foo: "default",
    bar: "value"
};

// if the user only specifies foo...
let userSpecifiedConfig: IConfig = {
    foo: "custom"
};

// let's create the final full config
// thought, it would be a good idea to use destructuring operator for that:

let wrongFinalConfig: IConfig = {
    ...userSpecifiedConfig,
    ...defaultConfig
}; // => not what we want: { foo: "default", bar: "value" }

let correctFinalConfig: IConfig = {
    ...defaultConfig,
    ...userSpecifiedConfig
}; // => this results in what we want, foo is overriden by user-config, bar has the default value: { foo: "custom", bar: "value" }

似乎以前设置的属性总是被以后设置的属性覆盖,因此在userSpecifiedConfig的情况下,在defaultConfig中设置的属性胜过correctFinalConfig。如果用户未定义它们,则仍然会有defaultConfig中的值。

此行为是已定义的还是不应该依赖于此销毁顺序?在后一种情况下,最干净的解决方案是从默认配置中覆盖未知的可选属性集?

0 个答案:

没有答案