Ilijanovic
Ilijanovic

Reputation: 14904

Typescript multidimensional array type

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?

Upvotes: 1

Views: 1765

Answers (2)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

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[][]]

Upvotes: 6

Anzor Asadov
Anzor Asadov

Reputation: 402

Id suggest something like this

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

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

Upvotes: 2

Related Questions