Search⌘ K

Generic Return Type, Optional Parameter and Default Value

Explore how to define generic return types, manage optional parameters using union types or the question mark syntax, and assign default values in TypeScript functions. Understand the implications of each approach to write clearer and more robust function signatures.

Function’s generic return type

TypeScript, since version 2.4, can infer the type of a function’s return value. Before version 2.4, s.length would give an error. The s was not from a U[] type but an empty object literal {}.

TypeScript 3.3.4
function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[] {
return a => a.map(f);
}
const lengths: (a: string[]) => number[] = arrayMap(s => s.length);

Function’s optional parameters

TypeScript lets you have optional parameters with different syntax. The first way to ...