TypeScript:联合类型分布的条件类型数组

标签 typescript discriminated-union

我有一个使用通用类型的条件类型 T确定 Array<T>类型。作为一个人为的例子:

type X<T> = T extends string ? Array<T> : never;

我遇到的问题是,当我提供一个联合类型时,它被分发为 2 个数组类型的联合,而不是我的联合类型的数组。

// compiler complains because it expects Array<'one'> | Array<'two'>
const y: X<'one' | 'two'> = ['one', 'two'];

有没有一种方法可以让我的条件类型产生一个 Array<'one' | '二'>如果满足条件?

最佳答案

您遇到了条件类型的分布行为,其中条件类型分布在包含联合的裸类型参数上。这种行为在某些情况下非常有用,但一开始可能有点令人惊讶。

禁用此行为的简单选项是将类型参数放在元组中:

type X<T> = [T] extends [string] ? Array<T> : never;

// ok y is Array<'one' | 'two'>
const y: X<'one' | 'two'> = ['one', 'two'];

您可以阅读有关此行为的更多信息 herehere

关于TypeScript:联合类型分布的条件类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53996797/

相关文章:

arrays - Firestore 无法使用 FieldValue.arrayUnion() 将项目数组合并到另一个数组

typescript - 无法使用 typescript 联合类型调用 Array.every()

.net - Haskell 在 F# 中的 "deriving Show"?

haskell - 受歧视类型工会

typescript - 分隔联合类型的每个成员

f# - 将 Elmish `dispatch` 消息从父组件传递/转换到子组件

javascript - 在带有书签的索引处将文本插入 TinyMCE 时丢失选择

javascript - 使用 Typescript 展平来自 Apollo/Hasura GraphQL 查询的结果

javascript - 如何获得无论哪一天都在两个小时范围内的时间?

f# - 受歧视工会中的 curry 争论