Utility types for unions and functions
Exclude, Extract and NonNullable for filtering unions; ReturnType, Parameters and Awaited for reading function types; NoInfer for steering inference.
Utility types for objectsUnion and literal typesDiscriminated unionsHow type argument inference works
Utility types for unions and functions
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `Exclude<T, U>` removes from the union `T` every member assignable to `U`, and `Extract<T, U>` keeps only those members; neither checks that `U` overlaps `T`, so a typo silently filters nothing.
- `Extract` with an object pattern such as `{ type: "keypress" }` pulls one variant out of a discriminated union.
- `NonNullable<T>` removes `null` and `undefined` from a type, which is the type-level version of a null check.
- `ReturnType` and `Parameters` read a function type, so they need `typeof fn` when given a function value; `Parameters` returns a labelled tuple that works with rest parameters and spreading.
- `ConstructorParameters` and `InstanceType` do the same job for classes, taking `typeof SomeClass` and giving the constructor's argument tuple and the instance type.
- `Awaited<T>` unwraps a promise type recursively, and `Awaited<ReturnType<typeof fn>>` is the standard way to name what an async function resolves to.
- `NoInfer<T>` (TypeScript 5.4) stops one parameter from contributing to the inference of `T`, so the type is decided by the other arguments and checked against this one.
Types you already have, in the wrong shape
The object utilities reshape a model’s properties. Two other kinds of reshaping come up just as often. Sometimes you have a union and need part of it: every status except "idle", or only the keyboard events. Other times the type you need is locked inside a function: what it returns, what it takes, what its promise resolves to.
You could write those types out by hand. But the union and the function already state them, and a copy drifts. The utilities in this lesson read them out instead.
Filtering unions: Exclude and Extract
Think of Exclude and Extract as a sieve. Each member of the union is tested on its own against a pattern; Exclude throws out the matches and Extract keeps only them.
type Status = "idle" | "loading" | "success" | "error";
type Settled = Exclude<Status, "idle" | "loading">; // "success" | "error"
type Busy = Extract<Status, "loading">; // "loading"
type AppEvent =
| { type: "click"; x: number; y: number }
| { type: "keypress"; key: string }
| { type: "scroll"; offset: number };
type KeyEvent = Extract<AppEvent, { type: "keypress" }>;
// { type: "keypress"; key: string }
type PointerFree = Exclude<AppEvent, { type: "click" }>;
“Matches” means “is assignable to,” which is why Extract with the pattern { type: "keypress" } picks the right variant out of a discriminated union: only that member has a type assignable to "keypress".
The same trap as Omit applies. The second argument isn’t checked against the first:
type Typo = Exclude<Status, "lodaing">; // no error; still all four members
Both are a few characters of standard library code built on distributive conditional types, which explain why each union member is tested separately.
NonNullable
NonNullable<T> removes null and undefined. It’s the type you have after a null check, useful when a field is nullable on the model but guaranteed present in some code path:
interface Employee {
name: string;
managerId: string | null;
}
type ManagerId = NonNullable<Employee["managerId"]>; // string
function notifyManager(id: ManagerId) {
console.log("notifying", id);
}
Reading function types: ReturnType and Parameters
Here’s a function whose result nobody bothered to name:
function createSession(userId: string, ttlSeconds: number) {
return {
token: Math.random().toString(36).slice(2),
userId,
expiresAt: Date.now() + ttlSeconds * 1000,
};
}
type Session = ReturnType<typeof createSession>;
// { token: string; userId: string; expiresAt: number }
type SessionArgs = Parameters<typeof createSession>;
// [userId: string, ttlSeconds: number]
type Wrong = ReturnType<createSession>; // Error: 'createSession' refers to a value
Both utilities take a function type, so a function value needs typeof first, exactly as in the typeof lesson. Parameters gives a labelled tuple, which slots straight into rest parameters. That makes wrappers easy to type:
function createSessionLogged(
...args: Parameters<typeof createSession>
): ReturnType<typeof createSession> {
console.log("creating session for", args[0]);
return createSession(...args);
}
type Ttl = Parameters<typeof createSession>[1]; // number
If createSession gains a parameter, the wrapper’s signature follows. One caveat: on an overloaded function, these utilities only see the last overload signature.
Classes have the matching pair ConstructorParameters and InstanceType:
class LruCache {
constructor(public name: string, public maxEntries: number) {}
}
type CacheArgs = ConstructorParameters<typeof LruCache>; // [name: string, maxEntries: number]
type CacheInstance = InstanceType<typeof LruCache>; // LruCache
typeof LruCache is the type of the class value, the constructor itself. InstanceType gives what new produces.
Awaited
An async function’s return type is always a promise, which is rarely the thing you want to name:
async function loadUser(id: string) {
return { id, name: "Ada" };
}
type Pending = ReturnType<typeof loadUser>; // Promise<{ id: string; name: string }>
type LoadedUser = Awaited<ReturnType<typeof loadUser>>; // { id: string; name: string }
type Nested = Awaited<Promise<Promise<number>>>; // number
Awaited models what the await keyword does. It unwraps the promise type, and keeps unwrapping while the result is still a promise, because at runtime promises never resolve to another promise. Awaited<ReturnType<typeof fn>> is common enough that you’ll start to read it as one word. Typing asynchronous code uses it heavily.
NoInfer
NoInfer<T>, added in TypeScript 5.4, solves a problem from how type argument inference works. When a type parameter appears in several parameters, every one of them votes on what T is:
function pickLoose<T extends string>(options: T[], fallback: T): T {
return options.includes(fallback) ? fallback : options[0];
}
pickLoose(["sm", "md", "lg"], "xl"); // compiles: T became "sm" | "md" | "lg" | "xl"
function pickDefault<T extends string>(options: T[], fallback: NoInfer<T>): T {
return options.includes(fallback) ? fallback : options[0];
}
pickDefault(["sm", "md", "lg"], "xl"); // Error: '"xl"' is not assignable
NoInfer removes fallback from the vote. T is decided by options alone, and fallback is then checked against it. The type of fallback is still T; only its influence on inference changes.
About the video
The embed starts at 10:05, the second half of Kyle Cook’s Web Dev Simplified utility types video. From there it covers Extract, Exclude, ReturnType, Parameters, ConstructorParameters, InstanceType, NonNullable and Awaited with clear examples, which is this lesson’s list. It doesn’t cover NoInfer. The Coding Szy video below does, and it also walks through the other utilities here, so it works as a second pass. basarat’s short video looks at how Awaited unwraps nested promises.
Check yourself
What is `Exclude<"idle" | "loading" | "error", "loading">`, and what would `Exclude<"idle" | "loading" | "error", "lodaing">` give?
The first is `"idle" | "error"`. The second is the full original union, with no error, because `Exclude` doesn't require its second argument to be a member of the first; the misspelled literal simply matches nothing.
Why does `ReturnType<createSession>` fail when `createSession` is a function declaration?
`ReturnType` takes a type argument, and `createSession` is a value. You first turn it into its function type with `typeof`, as in `ReturnType<typeof createSession>`.
How would you type a wrapper that takes exactly the same arguments as `createSession` and returns the same thing, without repeating the parameter list?
Use `(...args: Parameters<typeof createSession>): ReturnType<typeof createSession>` and call `createSession(...args)` in the body. If the original's parameters change, the wrapper's signature changes with it.
For `async function loadUser(id: string) { return { id }; }`, what is `ReturnType<typeof loadUser>` and how do you get the user type itself?
It is `Promise<{ id: string }>`, because an async function always returns a promise. `Awaited<ReturnType<typeof loadUser>>` unwraps the promise to `{ id: string }`.
In `pickDefault<T extends string>(options: T[], fallback: T)`, why does `pickDefault(["sm", "md"], "xl")` compile, and how does `NoInfer` change that?
Both parameters are inference sites, so TypeScript infers `T` as `"sm" | "md" | "xl"` and the call is valid. Typing the second parameter as `NoInfer<T>` means only `options` decides `T`, so `T` is `"sm" | "md"` and `"xl"` is rejected.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.