Home > database >  `[name: string]` syntax in typescript
`[name: string]` syntax in typescript

Time:04-19

I'm relatively new to Typescript, Today I faced with below syntax which I couldn't figure it out:

let aa:{
    [name: string]: boolean
}
aa ={
    ali: true,
    'text': false,
    3: true
}

What is [name: string]: boolean here?

At first, I thought it means we have unlimited number of properties inside aa object with keys types as string! But as you can see, I can define keys with any type.

CodePudding user response:

Index singatures may have keys in one of three types:

  • string
  • number
  • symbol (don't worry about this if you a beginner)

number in this case is actually just a subset of string, because number properties get stored on the object as strings.

This is true even in arrays. See:

const arr = ['a','b','c']
console.log(arr['0']) // 'a'

Which means that these two lines are identically equaivalent:

obj[3]
obj['3']

Which means that string keys include number keys. But if you declare number keys then typescript will enforce that, even though they are stored internally as strings.

const obj: { [key: number]: boolean } = { 3: true }

obj[3] // fine
obj['3'] // fine, because Typescript knows the string contains a number

const someString: string = '3'
obj[someString] // error

In conclusion, a string index signature will accept numbers, but a number index signature will only accept numbers or string literals that contain only diits.

  • Related