Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In typescript, what is the index signature identifier for?

Tags:

typescript

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;
}
like image 620
noop Avatar asked Jul 07 '13 19:07

noop


1 Answers

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.

like image 120
coudy Avatar answered Oct 27 '22 10:10

coudy