gpt4 book ai didi

typescript - 如何在 TypeScript 中引用属于联合类型的类型?

转载 作者:行者123 更新时间:2023-12-04 00:15:41 26 4
gpt4 key购买 nike

我在 TypeScript 中为 Action 定义了联合类型:

type Action = {
type: 'reset',
} | {
type: 'add',
payload: number
} | {
type: 'minus',
payload: number
}

在某些函数中,我想引用联合类型的一部分,比如:

function handleAdd(state: State, action: {
type: 'add',
payload: number
}): State => {
// handle the add
}

有没有办法简化action的输入所以我不需要重复

的完整定义
{
type: 'add',
payload: number
}

这里?

更新:

我不想单独预定义每个 Action 类型。是否有其他解决方案,例如 Action[type='add']

最佳答案

这可以通过 distributive conditional types 来实现:

type ExtractType<T extends Action['type'], A = Action> =
A extends { type: T } ? A : never;

type Add = ExtractType<'add'>; // { type: 'add'; payload: number; }

Playground

Distributive conditional types are automatically distributed over union types during instantiation. For example, an instantiation of T extends U ? X : Y with the type argument A | B | C for T is resolved as (A extends U ? X : Y) | (B extends U ? X : Y) | (C extends U ? X : Y)

关于typescript - 如何在 TypeScript 中引用属于联合类型的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64181463/

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