Sub topic 3
Generic Functions
Assume you know JavaScript functions, callbacks, arrays, union types, and how to run TypeScript with tsc.
Generic functions
A generic function uses a type parameter to preserve a relationship between its inputs and output. TypeScript often infers the type parameter from the arguments.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const name = first(["Ada", "Lin"]); // string | undefined
const score = first([10, 20]); // number | undefinedHere, T represents one type. The array and returned value use the same T.
Constraining type parameters
A constraint limits which types can be used. Use extends when the function needs a particular property or operation.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const word = longest("cat", "horse"); // string
const values = longest([1, 2], [3, 4, 5]); // number[]
// longest(1, 2); // Error: number has no lengthThe constraint allows access to length while keeping the result tied to the argument type.
Type predicates for narrowing
A type predicate is a return type such as value is string. A true result narrows the value inside that branch.
function isString(value: unknown): value is string {
return typeof value === "string";
}
function display(value: unknown): string {
return isString(value) ? value.toUpperCase() : String(value);
}Typing `this`
A first parameter named this declares the receiver type. It is removed from emitted JavaScript.
function describe(this: { name: string }): string {
return `I am ${this.name}`;
}
const person = { name: "Ada", describe };
person.describe(); // I am AdaAssignability and utility types
With strictFunctionTypes, a function accepting a broader parameter type can replace one accepting a narrower type. A function returning a narrower type can replace one returning a broader type. This protects callers from unsafe arguments and results.
Parameters<F> extracts a function's parameter tuple. ReturnType<F> extracts its return type.
function makeUser(id: number, name: string) {
return { id, name };
}
type UserArgs = Parameters<typeof makeUser>; // [id: number, name: string]
type User = ReturnType<typeof makeUser>; // { id: number; name: string }Exercise
What does longest require from each argument?
Show answer
Each argument must have a numeric length property, and the result keeps the argument type.