this my code
interface clients{
[key: string]: number
}
let x:clients = {}
I can’t understand why I can assign an empty object to x ?
this my code
interface clients{
[key: string]: number
}
let x:clients = {}
I can’t understand why I can assign an empty object to x ?
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.
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'
}