繁体   English   中英

Typescript:为什么 keyof Union 永远不会

[英]Typescript: why keyof Union is never

这是我的Typescript代码:

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运算符检查联合类型是否具有任何可共享属性。 在您的情况下, AB都没有相同的属性。

看下一个例子:


type A = { name: string, age: number }
type B = { name: string };

type Union = A | B

type key = keyof Union; // name

在这里,keyof 将返回“名称”。 因为这个属性在 A 和 B 中都存在。

问题出在| 操作员。 如果你用&代替它,你会得到你期望的结果:

interface Todo {
  title: string;
  content: string
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM