What does the index signature identifier do?
interface IIndex {
[something: string]: any;
}
Where would anyone use "something" again?
Or in other words, why isn't the syntax just:
interface IIndex {
[string]: any;
}
My guess would be that this is for reasons of consistency and closeness to JavaScript.
Just like it's common to name your method arguments (even in interfaces), all arguments to methods, constructors, functions and indexers in TS must be of the format name: type
or name
(meaning name: any
). (simplified version of the story but I'm sure you get me)
Since names and types live in different namespaces in TypeScript, an argument of the form string
would be ambiguous. Remember that TypeScript's mission is to stay close to JavaScript, so interpreting the above as an argument of type string
would be unacceptable, and turns out it is indeed equivalent to string: any
.
Furthermore, while indexers could be an exception, because they can only be of types string
or number
, this has not always been the case (TS 0.8 allowed any
), so another reason could be to facilitate migration to 0.9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With