1
interface SkillProperty {
    [name: string] : number 
};

let skills: SkillProperty;

skills = {}; // ok

skills = { fire: 123 }; // ok

skills = {
    ...skills, // ok
    ...{}, // ok
    ...extraSkills() // {} | { ice: number } is not assignable to type 'SkillProperty'.
}

function extraSkills() {
    if (whatever) {
        return {};
    }
    return { ice: 321 };
}

如何更改我的SkillProperty界面以使其符合空对象和我的实际 SkillProperty 类型?

4

1 回答 1

0

您的SkillProperty界面实际上兼容{} | {ice: number}

let noSkills = {}
let iceSkills = { ice: 321 };
let randomSkills: {} | {ice: number} = (Math.random() < 0.5) ? noSkills : iceSkills
let maybeSkills: SkillProperty = randomSkills; // no error

所以,对我来说,这看起来像是 TypeScript 中的一个错误。修复了类似的问题,但这种情况似乎仍然存在。打开一个新问题并链接到那些现有问题可能是值得的。

同时有一些解决方法,例如:

skills = {
  ...skills, // ok
  ...{}, // ok
  ...extraSkills() as SkillProperty // okay now
}

希望有帮助;祝你好运!

于 2017-09-13T19:09:36.097 回答