gpt4 book ai didi

typescript - typescript 中包含联合类型的对象的可区分联合

转载 作者:行者123 更新时间:2023-12-04 13:35:02 25 4
gpt4 key购买 nike

请建议一个更好的标题,我不知道到底要问什么。
我有一个看起来像这样的类型定义:

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']

关于typescript - typescript 中包含联合类型的对象的可区分联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62662936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com