简体   繁体   中英

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 .

The function arguments would be something like function merge<A, B>(elem: A, ar: B[]) . The result could be something like [A, B, B, B, ..., B] . The number of B elements and thus the total array length is unknown.

I know I could define a type like Array<A | B> Array<A | B> but this wouldn't give complete type safety cuz any element could be either A or B . I also know that I can define types like [A, B] , [A, B, B] and so on. But as I understand, those could only be used for arrays of known sizes.

Is there a way to define a type like [A, B, B, B, ..., B] in TypeScript?

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.

You might also have to cast the return statement as [A, ...[B]] to avoid type errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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