Generic Utility Types Generic Utility Types
Generic utility types can be used to process and transform different types of data. These generic utility types are generic because all they do is take the value of any other type and process it.
Partial
Make all properties of type
T
optional. Often used to temporarily switch an object type or an interface, making it optional. For example:1
2
3
4
5
6
7
8
9
10
11
12
13interface CourseGoal {
title: string;
description: string;
completeUntil: Date;
}
function createCourseGoal (title: string, description: string, completeUntil: Date): CourseGoal {
let courseGoal = Partial<CourseGoal> = {}; //If there is no Partial, an error will be reported.
courseGoal.title = title;
courseGoal.description = description;
courseGoal.completeUntil = date;
return courseGoal as CourseGoal;
}
Required
Makes all optional properties in type
T
required. For example:1
2
3
4
5
6
7
8
9
10interface Person {
name?: string;
age?: number;
address?: string;
}
type RequiredPerson = Required<Person>;
const person1: RequiredPerson = { name: 'Alice', age: 30, address: '123 Main St.' }; // OK
const person2: RequiredPerson = { name: 'Bob', age: 40 }; // Error: address is missing
Readonly
Makes all properties of type
T
read-only. For example:1
2
3
4
5
6
7
8
9
10interface Person {
name: string;
age: number;
address: string;
}
type ReadonlyPerson = Readonly<Person>;
const person: ReadonlyPerson = { name: 'Alice', age: 30, address: '123 Main St.' };
person.name = 'Bob'; // Error: Cannot assign to 'name' because it is a read-only property.It can also be used to lock arrays and objects, etc.
1
2const names: Readonly<string[]> = ["Max", "Anna"];
names.push("Manu"); //Error report
Pick<T, K>
Select the attribute named
K
from typeT
to form a new type. For example:1
2
3
4
5
6
7
8
9interface Person {
name: string;
age: number;
address: string;
email: string;
}
type PersonNameEmail = Pick<Person, 'name' | 'email'>;
const person: PersonNameEmail = { name: 'Alice', email: 'alice@example.com' };
Omit<T, K>
Remove the attribute named
K
from typeT
to form a new type. For example:1
2
3
4
5
6
7
8
9
10interface Person {
name: string;
age: number;
address: string;
email: string;
}
type PersonWithoutAge = Omit<Person, 'age'>;
const person: PersonWithoutAge = { name: 'Alice', address: '123 Main St.', email: 'alice@example.com' };
Record<K, T>
Creates a type containing a value type that maps each property name in type
K
to typeT
. For example:1
2
3
4
5
6
7
8
9
10type Weekday = 'Mon' | 'Tue' | 'Wed' | 'Thu' | 'Fri';
type WorkHours = Record<Weekday, { start: string, end: string }>;
const workHours: WorkHours = {
Mon: { start: '9:00', end: '17:00' },
Tue: { start: '9:00', end: '17:00' },
Wed: { start: '9:00', end: '17:00' },
Thu: { start: '9:00', end: '17:00' },
Fri: { start: '9:00', end: '17:00' },
}