Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Generic types

Generic types can help us avoid using type casting and increase the reusability of our code by allowing us to declare (T) when a function, class, or method is consumed, as opposed to when it is declared:

function deserialize<T>(json: string): T {
return JSON.parse(json) as T;
}

interface User {
name: string;
age: number;
}

let user = deserialize<User>(`{"name":"Remo","age":28}`);

interface Rectangle {
width: number;
height: number;
}

let rectangle = deserialize<Rectangle>(`{"width":5,"height":8}`);

The preceding example declares a function named deserialize. The type returned by the function (T) is unknown at the point in which the function is declared. The function is then invoked on two occasions, and the type T becomes finally known (User and Rectangle).

We will learn more about generic types in Chapter 4 , Object-Oriented Programming with TypeScript.