简体   繁体   English

Typescript:为什么 keyof Union 永远不会

[英]Typescript: why keyof Union is never

This is my Typescript code:这是我的Typescript代码:

interface Todo {
  title: string;
  content: string
}

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

My question is that why the type key is never?我的问题是为什么类型键永远不会?

Because extends works like intersection & .因为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 operator checks if union type has any sharable property. keyof运算符检查联合类型是否具有任何可共享属性。 In your case neither A nor B has not same property.在您的情况下, AB都没有相同的属性。

Take a look on next example:看下一个例子:


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

type Union = A | B

type key = keyof Union; // name

Here, keyof will return "name".在这里,keyof 将返回“名称”。 because this property exists in both A and B.因为这个属性在 A 和 B 中都存在。

The problem lies in the |问题出在| operator.操作员。 If you substitute it with & , you will get the result you expect:如果你用&代替它,你会得到你期望的结果:

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