typescript - 打字稿:为什么 keyof Union 永远不会
问题描述
这是我的打字稿代码:
interface Todo {
title: string;
content: string
}
type Union = Omit<Todo, 'content'> | {
name: string
};
type key = keyof Union; // never
我的问题是为什么类型键永远不会?
解决方案
因为extends
像交集一样工作&
。
interface Todo {
title: string;
content: string
}
// a bit simplified
type A = Omit<Todo, 'content'> // { title: string }
type B = { name: string };
type Union = A | B
type key = keyof Union; // never
keyof
运算符检查联合类型是否有任何可共享的属性。在您的情况下,既A
没有B
也没有相同的财产。
看下一个例子:
type A = { name: string, age: number }
type B = { name: string };
type Union = A | B
type key = keyof Union; // name
在这里,keyof 将返回“名称”。因为这个属性在 A 和 B 中都存在。
推荐阅读
- node.js - 如何在 MongoDB 2.2 中使用 $count 聚合运算符(或解决方法)?
- asp.net - 向 IdentityUser 添加数据注释
- macos - 为选项卡切换器添加 IntelliJ 快捷方式不会复制默认行为
- excel - 日期自动修改为其他内容
- jquery - 如何在页面重新加载时删除类/添加类
- android - Okhttp Authenticator addHeader() vs header()
- firebase - Firebase 无法更新值
- python - 我怎么可能创建一个模型的动态 REST API 链接,该链接会根据另一个模型的 id 进行更改?
- oracle - Oracle Developer Tools for Visual Studio 2017 安装无法启动
- css - 如何在角度选择新列表项时删除先前选择的列表项的活动类