首页 > 解决方案 > 打字稿:为什么 keyof Union 永远不会

问题描述

这是我的打字稿代码:

interface Todo {
  title: string;
  content: string
}

type Union = Omit<Todo, 'content'> | {
  name: string
};
type key = keyof Union; // never

我的问题是为什么类型键永远不会?

标签: typescript

解决方案


因为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 中都存在。


推荐阅读