The Exclude
type in TypeScript is a way to exclude certain types from a union.
Let's say you use a third-party package that exports a function with an optional parameter. The parameter uses an inline type which is not exported:
export function fetch(sortBy?: "name" | "date" | "rating") {}
You now want to extract the type of sortBy
but exclude undefined
from the union (undefined
is allowed because the param is optional).
You can use Parameters<T>
to get the parameters of the function and Exclude<T>
to exclude undefined
:
type SortBy = Exclude<Parameters<typeof fetch>[0], undefined>;
// Results in: type SortBy = "name" | "date" | "rating"