userMod2
userMod2

Reputation: 8960

Typescript - Type definition of object literal

I have an object like so - an int followed by a string, I tried setting the type like below, however it doesn't seem valid. I guess it's something really simple I'm missing.

const months: { int: string; } = { 
        0: 'JAN',
        1: 'FEB',
        2: 'MAR'
}

Update: I just found this works - correct?

const months: { [number: number]: string } = { ... }

or is my only generic option to use:

const months: any = { 
        0: 'JAN',
        1: 'FEB',
        2: 'MAR'
}

Thanks.

Upvotes: 0

Views: 333

Answers (1)

Anjil Dhamala
Anjil Dhamala

Reputation: 1622

What you're essentially saying is month is of type {int: string} where the created objects must have int property of type string. As in,

{
  int: '1' 
}

What you really want is a dictionary type and you'd create one like this.

const months: { [int: number]: string } = 
  { 
    0: 'JAN'
  }

Checkout this for further information.

Upvotes: 1

Related Questions