Write a function where the type of the input is related to the type of the output, or where the types of the two inputs are related in some way. Let’s consider a function that returns the first element of an array:

function firstElement(arr: any[]) { return arr[0]; } this function does its job, but unfortunately returns type Any. It would be better if the function returned the type of the array element.

In TypeScript, we use generics when we want to describe a relationship between two values. We do this by declaring a type parameter in the function signature:

function firstElement<T>(arr: T[]): T {

return arr[0];


const arr: string[] = [‘1’, ‘2’, ‘3’];

const result = firstElement(arr);


const result1:number = firstElement(arr);

Type inference function map

Output): Output[] { return arr.map(func); } Note that the Inout, Output of the above code can be replaced by T, V, but not as readable as the former.

We’ve written some general-purpose functions that can handle values of any Type. Sometimes we want to correlate two values, but we can only operate on a subset of a value. In this case, we can use constraints to restrict the type types that the type parameters can accept.

Let’s write a function that returns the longer of the two values. To do this, we need a length property, which is a number. We restrict the type parameter to that type by writing the extends clause:

function longest<Type extends { length: number }>(a: Type, b: Type) {

if (a.length >= b.length) {

return a;

} else {

return b;

} } // longerArray is of type ‘number[]’ const longerArray = longest([1, 2], [1, 2, 3]); console.log(longerArray); // longerString is of type ‘string’ const longerString = longest(“alice”, “bob”); console.log(longerString); // Error! Numbers don’t have a ‘length’ property const notOK = longest(10, 100); The last function call results in a compilation error because the TypeScript base type number does not have an attribute named length.

The power of TypeScript’s type constraints compared to Java is that extends does not have to be followed by a TypeScript built-in type, such as in this example:

{length: number} means that as long as the function is passed in a type that contains at least the length attribute of type number.

Specifying Type Arguments TypeScript can often, but not always, infer the expected Type Arguments in generic calls. For example, suppose you wrote a function to combine two arrays:

function combine

(arr1: Type[], arr2: Type[]): Type[] { return arr1.concat(arr2); } compiler error:

Solution: use Angle bracket syntax, explicitly introduced into type parameters: T = string here | number, mean to receive a string or number type.

Writing generic functions is fun, and it’s easy to get carried away with type arguments. Having too many types of mobile game arguments or using constraints where they are not needed can make reasoning less successful and frustrate the caller of the function.

1 – Ppush Type Parameters Down function firstElement1

(arr: Type[]) {return arr[0]; } function firstElement2

(arr: Type) { return arr[0]; } // a: number (good) const a = firstElement1([1, 2, 3]); // b: any (bad) const b = firstElement2([1, 2, 3]); At first glance, the two approaches seem the same, but firstElement1 is a better way to write this function. Its inferred return Type is Type, but the inferred return Type for firstElement2 is Any, because TypeScript must resolve the arr[0] expression using the constraint Type rather than “waiting” to resolve the element during the call.

Fewer Typewww.diuxie.com Parameters function filter1

(arr: Type[], func: (arg: Type) => Boolean): Fewer Typewww.diuxie.com Parameters function filter1

(arr: Type[], func: (arg: Type) => Boolean): Type[] { return arr.filter(func); } function filter2

boolean>( arr: Type[], func: Func ): Type[] { return arr.filter(func); } We create a type parameter Func that does not associate two values. This is always a red flag, because it means that the caller who wants to specify a type parameter must manually specify an additional type parameter for no reason at all. Func does nothing but make the function harder to read and reason about!

3-type Parameters Should Appear Twice function greet

(s: Str) {consol. log(“Hello, “+ s); } greet(“world”); In this example, Str occurs only once, so it’s not necessary at all.

It can be abbreviated as:

function greet(s: string) {

console.log(“Hello, ” + s);