How to use the spread operator in a typescript tuple?
Asked Answered
D

1

7

I want to specify how the rest of the array should look without knowing how many values the array will have. How can I achieve something like this? (playground version here):

type numStrArr = [number, ...string];

let arr: numStrArr = [1, 'hi', 'other string'];

The above code throws the error Type expected. at the spread operator, however.

I'm aware that there was a proposal for this, but how can I achieve similar behavior now?

Disforest answered 5/7, 2017 at 19:30 Comment(4)
You should probably use an object instead of an array.Sabo
I know that would work, I'm just interested how this would work aswellDisforest
I think this is impossible. You could use [number, string] or {0: number, [i: number]: string | number}, but both of them would type additional params as number | string, not string. Closest you could get is probably something like [number, string, string, string, string, string, string].Gorgeous
Played with this a bit, the best I could come up with is an interface extending Array. Playground link is too long. I can't really see any use case for this that isn't better handled by using objects...Cowgill
F
8

I know this question is 3 years old, but the feature is supported now. All you need to do is change the type to a type that can be spread. Read more about it here:


// no more error...
type numStrArr = [number, ...string[]];

Fudge answered 14/10, 2020 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.