当前打字稿不具有 https://github.com/Microsoft/TypeScript/issues/12936的一个概念确切的类型(对象文字有例外,我将在最后解释)。换句话说,某个接口的每个对象都可以具有额外的属性(接口中不存在这些属性)。
因此这个对象:
{
command: 34234,
children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
}
满足Type1
接口,因为它具有它的所有属性(command
) 属性,但它也满足Type2
接口,因为它具有它的所有属性(children
)也是如此。
关于对象字面量的注释:
typescript 确实仅针对对象文字实现了精确类型的概念:
export const unionType: Type1 = {
command: 34234,
children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }], // oops, not allowed here
};
export const unionType: Type2 = {
command: 34234, // oops, not allowed here
children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
};
上面是演示对象文字的代码,下面是没有它们的代码:
const someVar = {
command: 34234,
children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }]
};
const: Type1 = someVar // ok, because assigning not an object literal but a variable