I think I basically got how index signatures work in TypeScript. However, there is one thing I don't get. Given the following sample code:
const sales: {[ key: string ]: number } = {
a: 532,
b: 798,
c: 264
};
console.log(sales.a);
console.log(sales.d);
Now the compiler says, sales.a
and sales.d
are of type number
. But shouldn't that be number | undefined
, since the compiler can not know if a
and / or d
are actually there?
I can't come up with a specific interface here, because a
and d
are arbitrarily chosen at runtime, and not predefined.
I can solve this by using
{[ key: string ]: number | undefined }
as a type, but this seems to be cumbersome and annoying (and a pretty lame solution for a pretty trivial problem, given how objects are typically used in JavaScript).
So, one could say: To me, this seems counterintuitive: What sense do index signatures have, if they virtually enforce that for every possible string on earth there is also a value? For which type is this ever true?
Is there actually no easier solution for this than to come up with a
{[ …: string ]: … | undefined }
type over and over again? Nothing integrated into the language?
It's hard to believe that, given the fact that there are specialties such as Partial<T>
and co. … any thoughts on this?
PS: Is Record<T>
(semantically) the same as {[ key: string ]: T | undefined }
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…