1

this my code

interface clients{
    [key: string]: number
}
let x:clients = {}

I can’t understand why I can assign an empty object to x ?

Edgar
  • 6,022
  • 8
  • 33
  • 66
  • 1
    What error are you getting? Just tried in my environment and I'm not seeing any linting errors. – Nick Oct 26 '19 at 00:25
  • Related: [What does a TypeScript index signature actually mean?](https://stackoverflow.com/questions/58458308/what-does-a-typescript-index-signature-actually-mean) – ford04 Oct 26 '19 at 10:12

2 Answers2

4

Why wouldnt it work?

with [key: string]: number you basically say all property keys must be strings and the values must be numbers. Because for JS objects always all property keys are strings it just says, that all property values of this object must be numbers. It does not make any statement about how many properties the object must have. This could be zero (as in your example) or arbitrary many.

Lux
  • 17,835
  • 5
  • 43
  • 73
1

As mentioned in another answer, { [key: string]: number } indicates that any index of that type results in a number. {} is closer to Partial<{ [key: string]: number }> ({ [key: string]: number | undefined }).

You might also consider using Record<string, number>.

{ [key: string]: number | undefined } is a safer type, anyways, especially with strict mode enabled. When you index a value whose type is that, the resulting variable is of type number | undefined. It forces you to validate that result in JavaScript.

const client = x['clientId'] // type = number | undefined

if (client != undefined) {
  // typeof client === 'number'
}
Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62