I'm new to Typescript and I'm reading over someone else's code and having trouble with this declaration:
private somevar: { [s: string]: string };
What type is this? Square brackets indicate an array, but I'm confused about exactly what shape this would be in.
It's an indexable type. Looking at this variable definition's type expression:
let myIndexVar: { [key: string]: number; };
: { ... }
means it's an object.[key: string]: number;
is the index signature of the object.Within the index signature:
[key: string]
defines the name of the key—key
—and the type of the key—string
.: number;
is the type of the value—number
.These types are used like so:
let myIndexVar: { [key: string]: number; } = {};
myIndexVar["key"] = 4; // key is string, value is number
Note that you can give the key any name you like. Giving it a descriptive name is helpful to tell what the key is, though the variable name should also do that:
To further explain the answer by David Sherret
From the Typscript docs
Indexable Types Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example:
interface StringArray { [index: number]: string; } let myArray: StringArray; myArray = ["Bob", "Fred"]; let myStr: string = myArray[0];
Above, we have a StringArray interface that has an index signature. This index signature states that when a StringArray is indexed with a number, it will return a string.
There are two types of supported index signatures: string and number. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a number, JavaScript will actually convert that to a string before indexing into an object. That means that indexing with 100 (a number) is the same thing as indexing with "100" (a string), so the two need to be consistent.
class Animal { name: string; } class Dog extends Animal { breed: string; } // Error: indexing with a 'string' will sometimes get you a Dog! interface NotOkay { [x: number]: Animal; [x: string]: Dog; }
While string index signatures are a powerful way to describe the “dictionary” pattern, they also enforce that all properties match their return type. This is because a string index declares that obj.property is also available as obj["property"]. In the following example, name’s type does not match the string index’s type, and the type-checker gives an error:
interface NumberDictionary { [index: string]: number; length: number; // ok, length is a number name: string; // error, the type of 'name' is not a subtype of the indexer }
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