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 ...