1

Currently i have an array that has this type:

handlers: string[][]

It has for exapmle: [["click", "inc"], ["mousedown", "dec"]]

Now i want to change my structure to:

[[{ handler: "click", modifiers: ["enter"] }, "inc"]]

How do i define that the first element of my second arra is an object that contains an property called handler and modifiers?

2 Answers 2

6

Typescript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

So just use a type like:

handlers: [{handler: string, modifiers: string[]}, string][]

An alternative approach, when this type is only required on the first element:

interface MyInterface {
  [index: number]: string[] | [{handler: string, modifiers: string[]}, string];
  0: [{handler: string, modifiers: string[]}, string];
}

Or when the type is only valid in first place using Variadic tuple types

type MyType = [[{handler: string, modifiers: string[]}, string], ...string[][]]
Sign up to request clarification or add additional context in comments.

3 Comments

does this work too? [[{ handler: string, modifiers: string[] }, string]]
it would work if you limited the length of the outer array to a single element, like i wrote in the answer instead try [{ handler: string, modifiers: string[] }, string][]
@Ifaruki Just a hint regarding last alternative: You can already do that with TS 3.0 rest elements, in case v4.0 is not affordable yet.
2

Id suggest something like this

type NameOfType = {
  handler: string,
  modifiers: Array<string>,
}

const myThing: [[NameOfType, string]] = [[{ handler: "click", modifiers: ["enter"] }, "inc"]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.