NonNullable<T> / ReturnType<T> / Parameters<T>
| Since: | NonNullable<T> | TypeScript 2.0(2016) |
|---|---|---|
| ReturnType<T> | TypeScript 2.8(2018) | |
| Parameters<T> | TypeScript 3.1(2018) |
This section introduces utility types related to functions and null handling. NonNullable<T> removes null and undefined from a type, ReturnType<T> extracts the return type of a function, and Parameters<T> extracts a function's parameter types as a tuple. Awaited<T> recursively resolves a Promise type to its resolved value type.
Syntax
NonNullable<T> // Remove null and undefined from T ReturnType<T> // Return type of function type T Parameters<T> // Parameter types of function type T (as a tuple) Awaited<T> // Recursively resolved type of Promise<T>
Type Overview
| Type | Description |
|---|---|
| NonNullable<T> | Returns a type with null and undefined removed from T. |
| ReturnType<T> | Extracts the return type of function type T. |
| Parameters<T> | Extracts the parameter types of function type T as a tuple type. |
| Awaited<T> | Recursively resolves a Promise to get the type of its final value (TypeScript 4.5+). |
Sample Code
type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
// => string
// ReturnType
function greet(name: string): string {
return `Hello, ${name}`;
}
type GreetReturn = ReturnType<typeof greet>;
// => string
function fetchUser() {
return { id: 1, name: 'Ikari Shinji' };
}
type User = ReturnType<typeof fetchUser>;
// => { id: number; name: string }
// Parameters
function add(a: number, b: number): number {
return a + b;
}
type AddParams = Parameters<typeof add>;
// => [a: number, b: number]
// Awaited
type Resolved = Awaited<Promise<string>>;
// => string
type DeepResolved = Awaited<Promise<Promise<number>>>;
// => number
Notes
These utility types are especially useful when working with external libraries where you cannot define types yourself. For example, using ReturnType<typeof someLibraryFn> lets you automatically capture the return type of a library function.
Since Parameters<T> returns a tuple type, you can use index access to extract individual parameter types — for example, Parameters<typeof fn>[0] gives you the type of the first parameter.
Awaited<T> is handy when you need the resolved value type of an async function. Because an async function's return type is automatically wrapped in a Promise, using ReturnType<typeof asyncFn> alone would give you the Promise type. Combining them as Awaited<ReturnType<typeof asyncFn>> unwraps it to the actual resolved value type.
If you find any errors or copyright issues, please contact us.