这是我的打字稿代码:
interface Todo {
title: string;
content: string
}
type Union = Omit<Todo, 'content'> | {
name: string
};
type key = keyof Union; // never
我的问题是为什么 type 键从不?
答案 0 :(得分:3)
因为 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 将返回“name”。因为这个属性在 A 和 B 中都存在。
答案 1 :(得分:0)
问题在于 |
运算符。如果将其替换为 &
,则会得到您期望的结果:
interface Todo {
title: string;
content: string
}
type Union = Omit<Todo, 'content'> & {
name: string
};
type key = keyof Union; // "title" | "name"