Home > front end >  How to set a type of an array in an anonymous Object
How to set a type of an array in an anonymous Object

Time:02-10

How do I set the type of the array, because grid: []: number[] wont work

const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],  //Object literal's property 'grid' implicitly has an 'any[]' type.
  money: 600,
}

CodePudding user response:

You can type the whole object: (This is strongly recommended)

interface Game {
  sizeX: number
  sizeY: number
  SCALE: number
  grid: number[]
}

const game: Game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid: [],
  money: 600,
}

Or you can cast the empty array:

grid: [] as number[]

Or you can make the array non empty:

grid: [123]

To name a few

CodePudding user response:

The simplest is to use a variable (typed) to put your array, and than use it :

const grid: number[] = [];

const game = {
  sizeX: 9,
  sizeY: 5,
  SCALE: 80,
  grid,
  money: 600,
};
  • Related