July 2017
Intermediate to advanced
300 pages
5h 43m
English
The types we have just examined refer to a concrete type combination. In addition, TypeScript supports a so-called generic type that helps reusing the once created interface in different contexts. For example, if we want an interface for a data map, we can make it like this:
interface NumberDataMap {
[ key: string ]: number;
}
But this NumberDataMap accepts only numbers for the member values. Let's say, for string values, we have to create a new interface, such as StringDataMap. Alternatively, we can declare a generic DataMap that sets an arbitrary value type constraint when referred:
interface DataMap<T> { [ key: string ]: T; } const numberMap: DataMap<number> = { foo: 1, bar: 2 }, stringMap: DataMap<string> = { foo: "foo", ...Read now
Unlock full access