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

编程入门 行业动态 更新时间:2024-10-22 16:39:36
本文介绍了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:联合类型分布的条件类型数组

本文发布于:2023-05-29 23:10:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355109.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   数组   条件   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!