Sub topic 9
Working with members: Extract and indexed access
This chapter assumes you can read TypeScript generics and conditional types at a basic level, and that strict: true is on. It also assumes you have a discriminated union like the Shape type from earlier chapters. Here you will learn how to pull pieces out of a union without copying them by hand.
Why derive types from the union
Suppose you have this union:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };Sooner or later you need a type for one member only. An example is a makeCircle function that returns just the circle shape. You could write a separate Circle interface and make Shape a union of such interfaces. You could also write the circle type a second time. The second option creates two definitions that can drift apart.
TypeScript offers a better route. You keep one definition, the union, and derive everything else from it. If someone renames radius to r, every derived type updates, and the compiler flags the code that still uses the old name.
Two tools do most of the work:
Extract<T, U>selects the members of a unionTthat are assignable toU.- Indexed access, written
T["key"], reads the type of a property. On a union, it reads that property from every member and returns the union of the results.
Extract: selecting members by tag
Extract filters a union. It keeps each member that is assignable to the second argument and drops the rest.
type Circle = Extract<Shape, { kind: "circle" }>;
// { kind: "circle"; radius: number }
type ShapeKind = Shape["kind"];
// "circle" | "square" | "rectangle"The pattern { kind: "circle" } is a small object type with one property. The circle member is assignable to it, because it has a kind of "circle" and extra properties are fine. The square and rectangle members are not assignable, because their kind is a different literal.
How Extract works internally
The standard library defines it like this:
type MyExtract<T, U> = T extends U ? T : never;This is a distributive conditional type. When T is a bare type parameter and you pass a union, TypeScript applies the condition to each member separately and then joins the results. For Shape and { kind: "circle" }, the evaluation goes like this:
- The circle member extends
{ kind: "circle" }, so it stays. - The square member does not, so it becomes
never. - The rectangle member does not, so it becomes
never. - The union of
circle | never | neveris justcircle.
Because never disappears from unions, you are left with the members that matched.
Extracting several members at once
The second argument can itself be a union. Extract keeps every member assignable to any part of it.
type RoundOrSquare = Extract<Shape, { kind: "circle" | "square" }>;
// { kind: "circle"; radius: number } | { kind: "square"; size: number }This works because a member with kind: "circle" is assignable to { kind: "circle" | "square" }. The property type on the right accepts either literal.
Exclude and Omit
Exclude<T, U> is the opposite of Extract. It removes members assignable to U.
type NotCircle = Exclude<Shape, { kind: "circle" }>;
// { kind: "square"; size: number } | { kind: "rectangle"; width: number; height: number }Be careful with Omit on a union. Omit<Shape, "kind"> is not distributive. It flattens the union first and keeps only keys common to all members, so you lose radius, size, width, and height. The result is {}. When you need to strip a property from every member, write a distributive version.
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown
? Omit<T, K>
: never;
type ShapeWithoutKind = DistributiveOmit<Shape, "kind">;
// { radius: number } | { size: number } | { width: number; height: number }The T extends unknown check looks pointless, but it triggers distribution over the members of T.
Indexed access on unions
Indexed access reads a property type. On a single object type it behaves as you would expect.
type Radius = Extract<Shape, { kind: "circle" }>["radius"];
// numberOn a union, the key must exist in every member. That is why Shape["kind"] works and Shape["radius"] does not.
type Kinds = Shape["kind"]; // "circle" | "square" | "rectangle"
// Error: Property 'radius' does not exist on type 'Shape'.
// type Bad = Shape["radius"];Shape["kind"] is useful because it stays in sync with the union. Adding a triangle member extends ShapeKind automatically.
Using the derived tag type
A common use is a lookup table that must have an entry for every kind. A mapped type over ShapeKind makes the compiler enforce that.
const labels: Record<Shape["kind"], string> = {
circle: "Circle",
square: "Square",
rectangle: "Rectangle",
};If you add a new member to Shape and forget to add a label, the object literal is missing a required property and the compiler reports an error. This gives you exhaustiveness checking for data, in the same spirit as the never check for switch statements.
Building a member lookup by tag
You can combine both tools into a helper that returns the member for a given tag. This avoids repeating the Extract pattern.
type ShapeOf<K extends Shape["kind"]> = Extract<Shape, { kind: K }>;
type Square = ShapeOf<"square">;
// { kind: "square"; size: number }The constraint K extends Shape["kind"] rejects tags that do not exist, so ShapeOf<"triangle"> is a compile error. You can use this in function signatures to tie an argument to a return type.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
type ShapeOf<K extends Shape["kind"]> = Extract<Shape, { kind: K }>;
function isKind<K extends Shape["kind"]>(
shape: Shape,
kind: K,
): shape is ShapeOf<K> {
return shape.kind === kind;
}
const shapes: Shape[] = [
{ kind: "circle", radius: 2 },
{ kind: "square", size: 3 },
{ kind: "circle", radius: 5 },
];
const circles = shapes.filter((s): s is ShapeOf<"circle"> => isKind(s, "circle"));
const radii = circles.map((c) => c.radius);
console.log(radii); // [2, 5]The return type shape is ShapeOf<K> is a type predicate. When isKind(shape, "circle") returns true, TypeScript narrows shape to the circle member. The filter call uses an explicit predicate so the resulting array has the narrowed element type.
Extracting from any discriminant
The same pattern works for unions with a different tag name. If you want a helper that works for any discriminated union and any tag key, add generic parameters.
type ByTag<U, K extends keyof U, V extends U[K]> = Extract<U, Record<K, V>>;
type Circle2 = ByTag<Shape, "kind", "circle">;
// { kind: "circle"; radius: number }This version has a trap. keyof U on a union returns only the keys common to all members, so K can be "kind" here. That is what you want for a discriminant, because the tag must exist on every member. It would reject "radius", which is correct.
Edge cases and gotchas
- Widened tags.
Extractonly matches members whose tag is a literal type. If a member declareskind: string, it is assignable to nothing narrower, and your extraction returnsnever. Keep tags as literals. - Optional tags. If a member has
kind?: "circle", the pattern{ kind: "circle" }does not match it, because an optional property is not assignable to a required one. Make the tag required. - Empty results. A misspelled tag in
Extractgivesneverwith no error. Prefer theShapeOf<K>form with a constraint, which rejects bad tags. - Overlapping members. If two members both match the pattern,
Extractreturns both. That is correct behavior, but it can surprise you when a member has a wider tag union. - Intersections. If a union member is an intersection, such as
Base & { kind: "x" },Extractstill works, because assignability is checked on the combined type.
Putting it together
The diagram shows how the derived types relate to the one union you maintain.
You edit the union in one place. The tag union, the per-member types, the lookup table, and the type predicate all follow from it.
Exercise
Given type Event = { type: "click"; x: number; y: number } | { type: "key"; code: string } | { type: "scroll"; delta: number }, write a type KeyEvent that selects only the key member, and a type EventType that is the union of all tag values. What does Event["x"] produce?
Show answer
type KeyEvent = Extract<Event, { type: "key" }>; gives { type: "key"; code: string }. type EventType = Event["type"]; gives "click" | "key" | "scroll". Event["x"] is a compile error, because x does not exist on every member of the union, and indexed access on a union requires the key to be present in all members.
Exercise
Omit<Shape, "kind"> returns {} instead of the members without their tag. Why, and how do you fix it?
Show answer
Omit is not distributive. It applies keyof to the whole union, which yields only the keys shared by all members, and then removes "kind", which leaves no keys. Define type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never; so the conditional type distributes and Omit runs once per member.