TypeScript:联合类型分布的条件类型数组 [英] TypeScript: Conditional type array of union type distribution

查看:385
本文介绍了TypeScript:联合类型分布的条件类型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个条件类型,它使用通用类型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:联合类型分布的条件类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆