0brine
0brine

Reputation: 486

How to set a type of an array in an anonymous Object

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,
}

Upvotes: 0

Views: 1404

Answers (2)

JeromeBu
JeromeBu

Reputation: 1159

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,
};

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187004

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

Upvotes: 2

Related Questions