Types built into TypeScript that help with common type manipulation.
Makes all properties in an object optional.
interface Coords {
x: number;
y: number;
}
let coordsPart: Partial<Coords> = {}; // `Partial` allows x
// and y to be optional
coordsPart.x = 10;
Makes all properties in an object required.
interface Vehicle {
make: string;
model: string;
mileage?: number;
}
let myCar: Required<Vehicle> = {
make: "Honda",
model: "Civic",
mileage: 30000, // `Required` forces mileage to be defined
};
Creates an object type whose property keys are Keys and whose property values are Type.
const ageNameMap: Record<string, number> = {
Matt: 20,
Michael: 24,
};
//`Record<string, number>` is the same as `{ [key: string]: number }`
Remove specific keys from an object type:
interface Employee {
name: string;
age: number;
location?: string;
}
// Only name is allowed - age and location are omitted
const matt: Omit<Employee, "age" | "location"> = {
name: "Matt",
};
Keeps only the specified keys (opposite of Omit).
// Only name is allowed - everything else is excluded
const michael: Pick<Employee, "name"> = {
name: "Michael",
};
Removes types from a union.
type Primitive = string | number | boolean;
const value3: Exclude<Primitive, string> = true; // a string cannot
// be used since Exclude removed it from the type.
Extracts return type from function type.
type CoordGenerator = () => { x: number; y: number };
const coord: ReturnType<CoordGenerator> = {
x: 10,
y: 20,
};
Extracts the parameters types from a function (as an array).
type CoordPrinter = (p: { x: number; y: number }) => void;
const coord2: Parameters<CoordPrinter>[0] = {
x: 10,
y: 20,
};