typescript - 打字稿类型在使用联合类型的对象文字分配上丢失
问题描述
我希望下面的代码会出错,但是打字稿完全没问题,你能告诉我为什么吗?
export interface Type1 {
command: number;
}
export interface Type2 {
children: string;
}
export type UnionType = Type1 | Type2;
export const unionType: UnionType = {
command: 34234,
children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
};
这是链接。
解决方案
Typescript 目前没有确切类型的概念(对象字面量有例外,我会在最后解释)。换句话说,某个接口的每个对象都可以有额外的属性(接口中不存在这些属性)。
因此这个对象:
{
command: 34234,
children: [{ foo: 'qwerty' }, { asdf: 'zxcv' }],
}
满足Type1
接口,因为它具有所有属性 ( command
) 属性,但它也满足Type2
接口,因为它也具有所有属性 ( children
)。
关于对象文字的注释:打字稿确实为对象文字实现了精确类型的概念:
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
推荐阅读
- php - 如何在 Vagrant 和 Homestead 中回滚 PHP 版本?
- html - 文本对齐适用于一个标签但不适用于另一个标签?
- wordpress - 无法同时从本地和外部访问 Wordpress 站点
- r - 如何绘制角度在 0-360 度之间的线
- c# - Convert Char[] to Int,战争纸牌游戏
- python - 有没有更好的方法来记住 Python 中先前给出的可选方法参数?
- ascii - 是否有各种空格的编译:ascii 和非 ascii 空格?
- javascript - 我正在尝试将一个类添加到某个 div,它只是将它添加到具有此 ID 的 div 之一,为什么?
- bash - 如果文件为空则退出 1 否则继续下一步
- sql - Rails:ActiveRecord 星期几