简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM