Home > database >  How to declare an object filled with arrays?I
How to declare an object filled with arrays?I

Time:10-08

I want to declare a variable that is an object filled with arrays for example:

let obj = {
    "page1"     : [ {x: 1, y: 2}, {x: 2, y: 5} ],
    "page2"     : [ {x: 1, y: 2}, {x: 2, y: 5} ],
    "dsfsfffsfs": [ {x: 1, y: 2}, {x: 2, y: 5} ]
}

How can I declare that as an interface in typescript?

CodePudding user response:

If you will always have number elements in your arrays, you can type it using the type utility Record<Keys, Type>:

Record<string, number[]>

where the keys are strings and the values are number[] (arrays of numbers) like this:

TS Playground

let obj: Record<string, number[]> = {
  page1: [ 1, 2, 3 ],
  page2: [ 2, 3, 4 ],
  dsfsfffsfs: [ 1, 2, 3 ],
};

However, you can also create your own type utility that allows you to provide a generic type parameter for the array elements:

TS Playground

type ObjectOfArray<T> = Record<string, T[]>;

// The same as { x: number; y: number; }
type CartesianCoordinates = Record<'x' | 'y', number>;

let obj: ObjectOfArray<CartesianCoordinates> = {
  page1: [ {x: 1, y: 2}, {x: 2, y: 5} ],
  page2: [ {x: 1, y: 2}, {x: 2, y: 5} ],
  dsfsfffsfs: [ {x: 1, y: 2}, {x: 2, y: 5} ],
};


And if the arrays should always have exactly 2 elements, then you can use a tuple type to indicate that:

TS Playground

type CartesianCoordinates = Record<'x' | 'y', number>;

let obj: Record<string, [CartesianCoordinates, CartesianCoordinates]> = {
  page1: [ {x: 1, y: 2}, {x: 2, y: 5} ],
  page2: [ {x: 1, y: 2}, {x: 2, y: 5} ],
  dsfsfffsfs: [ {x: 1, y: 2}, {x: 2, y: 5} ],
};

CodePudding user response:

As you said you want interface. One way to do it is like this.

interface xx {
    x : number,
    y : number,
}
interface yy {
    "page1" : xx[],
    "page2" : xx[],
    "dsfsfffsfs" : xx[]
}
  • Related