我有一个条件类型,它使用通用类型T来确定Array<T>类型.举一个人为的例子:
I have a conditional type that uses a generic type T to determine an Array<T> type. As a contrived example:
type X<T> = T extends string ? Array<T> : never;我遇到的问题是,当我提供联合类型时,它以2个数组类型的联合而不是我的联合类型的数组形式分发.
The issue I am having is when I provide a union type, it is being distributed as a union of 2 array types instead of an array of my union type.
// compiler complains because it expects Array<'one'> | Array<'two'> const y: X<'one' | 'two'> = ['one', 'two'];有没有一种方法可以键入此值,以便我的条件类型产生Array<'one'| 'two'>是否满足条件?
Is there a way to type this such that my conditional type produces an Array<'one' | 'two'> if the condition is met?
推荐答案您已经遇到了条件类型的分布行为,其中条件类型分布在包含联合的裸类型参数上.这种行为在某些情况下非常有用,但起初可能会有些意外.
You have run into the distributive behavior of conditional types where a conditional type is distributed over a naked type parameter containing a union. This behavior is very useful in some scenarios but can be a bit surprising at first.
禁用此行为的简单方法是将type参数放入元组:
The simples option to disable this behavior is to put the type parameter in a tuple:
type X<T> = [T] extends [string] ? Array<T> : never; // ok y is Array<'one' | 'two'> const y: X<'one' | 'two'> = ['one', 'two'];您可以在此处和此处
更多推荐
TypeScript:联合类型分布的条件类型数组
发布评论