TypeScript provides a variety of utility types and advanced types that help with common type transformations. These utility types are built into TypeScript and can be used to manipulate and transform types in various ways. Below is a comprehensive list of all the utility types and advanced types in TypeScript.
1. Partial<T>
Constructs a type with all properties of T
set to optional.
interface User {
id: number;
name: string;
age: number;
}
type PartialUser = Partial<User>;
// Equivalent to:
// {
// id?: number;
// name?: string;
// age?: number;
// }
2. Required<T>
Constructs a type with all properties of T
set to required.
interface User {
id?: number;
name?: string;
age?: number;
}
type RequiredUser = Required<User>;
// Equivalent to:
// {
// id: number;
// name: string;
// age: number;
// }
3. Readonly<T>
Constructs a type with all properties of T
set to read-only.
interface User {
id: number;
name: string;
}
type ReadonlyUser = Readonly<User>;
// Equivalent to:
// {
// readonly id: number;
// readonly name: string;
// }
4. Record<K, T>
Constructs an object type whose keys are K
and values are T
.
type UserRoles = Record<string, boolean>;
// Equivalent to:
// {
// [key: string]: boolean;
// }
const roles: UserRoles = {
admin: true,
user: false,
};
5. Pick<T, K>
Constructs a type by picking a set of properties K
from T
.
interface User {
id: number;
name: string;
age: number;
}
type UserNameAndAge = Pick<User, 'name' | 'age'>;
// Equivalent to:
// {
// name: string;
// age: number;
// }
6. Omit<T, K>
Constructs a type by omitting a set of properties K
from T
.
interface User {
id: number;
name: string;
age: number;
}
type UserWithoutAge = Omit<User, 'age'>;
// Equivalent to:
// {
// id: number;
// name: string;
// }
7. Exclude<T, U>
Excludes from T
all types that are assignable to U
.
type T = string | number | boolean;
type U = string | boolean;
type Result = Exclude<T, U>; // Result is `number`
8. Extract<T, U>
Extracts from T
all types that are assignable to U
.
type T = string | number | boolean;
type U = string | boolean;
type Result = Extract<T, U>; // Result is `string | boolean`
9. NonNullable<T>
Excludes null
and undefined
from T
.
type T = string | number | null | undefined;
type Result = NonNullable<T>; // Result is `string | number`
10. ReturnType<T>
Constructs a type consisting of the return type of function T
.
function getUser() {
return { id: 1, name: 'John' };
}
type UserReturnType = ReturnType<typeof getUser>;
// Equivalent to:
// {
// id: number;
// name: string;
// }
11. InstanceType<T>
Constructs a type consisting of the instance type of a constructor function T
.
class User {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
type UserInstance = InstanceType<typeof User>; // Equivalent to `User`
12. ThisParameterType<T>
Extracts the type of this
parameter of a function type
function getUser(this: { id: number }) {
return this.id;
}
type ThisType = ThisParameterType<typeof getUser>; // { id: number }
13. OmitThisParameter<T>
Removes this
parameter from a function type T
.
function getUser(this: { id: number }) {
return this.id;
}
type FunctionWithoutThis = OmitThisParameter<typeof getUser>; // () => number
14. Parameters<T>
Constructs a tuple type from the parameter types of a function type T
.
function getUser(id: number, name: string) {
return { id, name };
}
type UserParams = Parameters<typeof getUser>; // [number, string]
15. ConstructorParameters<T>
Constructs a tuple type from the parameter types of a constructor function type T
.
class User {
constructor(public id: number, public name: string) {}
}
type UserConstructorParams = ConstructorParameters<typeof User>; // [number, string]
Advanced Types
1. Conditional Types
Conditional types allow you to define types based on conditions.
type IsString<T> = T extends string ? true : false;
type A = IsString<'hello'>; // true
type B = IsString<123>; // false
2. Mapped Types
Mapped types allow you to create new types by transforming properties of existing types.
type Optional<T> = {
[K in keyof T]?: T[K];
};
interface User {
id: number;
name: string;
}
type OptionalUser = Optional<User>;
// Equivalent to:
// {
// id?: number;
// name?: string;
// }
3. Template Literal Types
Template literal types allow you to create new string literal types by combining existing ones.
type EventName = 'click' | 'scroll';
type EventHandler = `on${Capitalize<EventName>}`; // 'onClick' | 'onScroll'
4. Recursive Types
Recursive types allow you to define types that reference themselves.
type Json =
| string
| number
| boolean
| null
| { [key: string]: Json }
| Json[];
const data: Json = {
name: 'John',
age: 30,
hobbies: ['reading', 'coding'],
};
5. Index Access Types
Index access types allow you to access the type of a property of another type.
interface User {
id: number;
name: string;
}
type UserId = User['id']; // number
type UserName = User['name']; // string
6. Keyof Operator
The keyof
operator creates a union type of all the keys in an object type.
interface User {
id: number;
name: string;
}
type UserKeys = keyof User; // 'id' | 'name'
7. Type Assertions
Type assertions allow you to specify the type of a value explicitly.
let value: any = 'hello';
let length = (value as string).length; // Type assertion
8. Type Guards
Type guards allow you to narrow down the type of a variable within a conditional block.
function isString(value: any): value is string {
return typeof value === 'string';
}
let value: string | number = 'hello';
if (isString(value)) {
console.log(value.toUpperCase()); // Type narrowed to `string`
}
Typescript's utility and advanced types are a game-changer for developers looking to write robust and maintainable code. From simplifying type transformations with Partial
, Pick
, and Omit
to creating complex conditional and recursive types, these tools empower you to handle a wide range of scenarios with ease. By mastering these types, you can significantly improve your productivity and reduce the likelihood of runtime errors in your applications.
Top comments (0)