打字稿中包含联合类型的对象的区别联合

时间:2020-06-30 17:24:30

标签: typescript

请提出一个更好的标题,我不确定要问什么。

我有一个看起来像这样的类型定义:

type Animal =
  | {
    'species': 'cat'
    'action': 'meow'
  }
  | {
    'species': 'cat'
    'action': 'whine'
  }
  | {
    'species': 'dog' | 'tree'
    'action': 'bark'
  };

我想定义一个条件类型ActionsFor<S>,该条件类型导致给定物种的范围缩小。例如:

type CatActions = ActionsFor<'cat'> // should be 'meow' | 'whine'
type DogActions = ActionsFor<'dog'> // should be 'bark'
type TreeActions = ActionsFor<'tree'> // should be 'bark'
type BarkActions = ActionsFor<'dog'|'tree'> // should be 'bark'

我目前的尝试接近完成,但对于联合物种却无法正常工作

type ActionFor<S extends Animal['species']> = Extract<Animal, {species: S}>['action']

这将导致:

type CatActions = ActionsFor<'cat'> // correct - 'meow' | 'whine'
type DogActions = ActionsFor<'dog'> // WRONG - never
type TreeActions = ActionsFor<'tree'> // WRONG - never
type BarkActions = ActionsFor<'dog'|'tree'> // correct - 'bark'

如何重新定义ActionsFor以执行我想要的操作?

1 个答案:

答案 0 :(得分:1)

弄清楚了。这似乎可行,但是如果有人可以使它更短或更优雅,那么我将不知所措!

type ActionFor<S extends Animal['species']> = Exclude<Animal, {species: Exclude<Animal['species'], S>}>['action']
相关问题