簡體   English   中英

typescript 中包含聯合類型的對象的可區分聯合

[英]Discriminated unions of objects containing union types in 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 來做我想做的事?

弄清楚了。 這似乎可行,但如果有人可以讓它更短或更優雅,我會全力以赴!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM