1

I have created my own type called tuple, and I want to make an array, of length 10, with elements of type tuple. How do I do that (possibly) with that specific Array syntax, or any other?

type tuple =  [number, number]

var numbers: Array<tuple> = []
3
  • Make it a tuple of tuples? Commented Sep 22, 2022 at 16:59
  • There's nothing wrong with your posted code. Do you mean that you want a type that is a tuple of 10 of the [number, number] tuple type? Or do you want to create a tuple[] array at runtime with 10 items in it? Which part there are you having trouble with? Please edit your question and add some information about your desired result. Commented Sep 22, 2022 at 17:39
  • Sorry for bad explaining. Desired outcome is to have an array of length 10, where every item is of type tuple, so I could just ,for example, in very next line say numbers[3] = [3,15]; without actually having to push items first to get 3rd spot Commented Sep 22, 2022 at 17:56

2 Answers 2

1

Just to add a separate answer if you're okay with having default values for your tuple, something like this could work:

type tuple = [number, number]
type TupleArray<tuple, TupleLen extends number> = [tuple, ...tuple[]] & { length: TupleLen }

let numbers: TupleArray<tuple, 10> = Array(10).fill([0, 0]) as TupleArray<tuple, 10>;

With this approach, you're specifically typing TupleArray to have a specific length, so there is the added caveat of an empty array or any array above or below a length of 10 would throw an error. This is also why you need to fill your array with 10 tuples.

Sign up to request clarification or add additional context in comments.

Comments

0

Make it a tuple of tuples? Or specifically, a tuple of the type tuple you already have.

type tuple =  [number, number];

const numbers: [tuple, tuple, tuple, tuple, ...] = [...];

1 Comment

Actually haven't thought about it. But this could be hard if I want higher array lengths. Of course I could push empty elements, but was hoping for neat solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.