In this article, i'm going to cover 10 typescript utilities every developer should know.
- Partial type
- Required type
- Readonly
- Pick
- Omit
- Record
- Exclude
- Extract
- NonNullable
- Return type
1- Partial type
Type Person = {
name: string;
age: number;
gender: string;
address: string;
}
// Partial<T> type Partial sets all properties
// of Person to optional
type PartialPerson = Partial<Person>;
2-Required
// Required<T> all properties of `RequiredPerson`
// are required
type RequiredPerson = Required<Person>;
3-Readonly
// Readonly<T>: Creates a type with all properties
// of T set to readonly.
type ReadonlyPerson = Readonly<Person>;
4-Pick
// Creates a type by picking only the specified
// properties K from T.
type PersonName = Pick<Person, 'name'>;
5-Omit
// Omit<T,K> Creates a type by omitting the specified
// properties K from T.
type PersonWithoutAge = Omit<Person, 'age'>;
6-Record
// Record<K,T> Creates a type with keys of type
// K and values of type T.
type StringRecord = Record<string, Person>;
7-Exclude
// Exclude<T, U>: Creates a type by excluding all types
// from T that are assignable to U.
// string is excluded from the union type
type NumbersOnly = Exclude<number | string, string>;
8-Extract
// Extract<T, U> Creates a type by extracting all types
// from T that are assignable to U.
// string is extract from the union type
type StringOnly = Extract<number | string, string>;
9-NonNullable
// NonNullable<T>: Creates a type by removing null and undefined from T.
// null and undefined are excluded from the union type
type NonNullString = NonNullable<string | null | undefined>;
10-ReturnType
// ReturnType<T>: Obtains the return type of a function type.
type MyFunctionReturnType = ReturnType<MyFunction>;
Top comments (0)