简体   繁体   English

TypeScript:定义未知大小的数组类型,其中第一个元素属于 A 类型,rest 元素属于 B 类型

[英]TypeScript: define array type of unknown size where first element is of type A and rest elements are of type B

I have a function that merges element of type A with some array of elements of type B .我有一个 function 将A类型的元素与B类型的一些元素数组合并。

The function arguments would be something like function merge<A, B>(elem: A, ar: B[]) . function arguments 类似于function merge<A, B>(elem: A, ar: B[]) The result could be something like [A, B, B, B, ..., B] .结果可能类似于[A, B, B, B, ..., B] The number of B elements and thus the total array length is unknown. B 元素的数量以及总数组长度是未知的。

I know I could define a type like Array<A | B>我知道我可以定义一个像Array<A | B> Array<A | B> but this wouldn't give complete type safety cuz any element could be either A or B . Array<A | B>但这不会提供完整的类型安全性,因为任何元素都可以是AB I also know that I can define types like [A, B] , [A, B, B] and so on.我也知道我可以定义[A, B] , [A, B, B]等类型。 But as I understand, those could only be used for arrays of known sizes.但据我了解,这些只能用于已知尺寸的 arrays 。

Is there a way to define a type like [A, B, B, B, ..., B] in TypeScript?有没有办法在 TypeScript 中定义像[A, B, B, B, ..., B]这样的类型?

Alright, found an answer to this.好的,找到了这个问题的答案。 In typescript starting from version 3 you can define destructuring types like [A, ...[B]] which will give the desired result.在从版本 3 开始的 typescript 中,您可以定义解构类型,如[A, ...[B]] ,这将给出所需的结果。

You might also have to cast the return statement as [A, ...[B]] to avoid type errors.您可能还必须将 return 语句转换as [A, ...[B]]以避免类型错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM