TypeScript: Conditional type array of union type distribution

本秂侑毒 提交于 2019-12-10 20:24:22

问题


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;

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

Is there a way to type this such that my conditional type produces an Array<'one' | 'two'> if the condition is met?


回答1:


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.

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

You can read more about this behavior here and here



来源:https://stackoverflow.com/questions/53996797/typescript-conditional-type-array-of-union-type-distribution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!