Sub topic 3
Working with Members: Extract and Indexed Access
Assume strict: true, basic object types, unions, functions, and if and switch statements.
Extracting union members
A discriminated union has several object members that share a tag property:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
type Circle = Extract<Shape, { kind: "circle" }>;
// { kind: "circle"; radius: number }
type ShapeKind = Shape["kind"];
// "circle" | "square" | "rectangle"Extract<Union, Condition> keeps only members assignable to Condition. Indexed access, such as Shape["kind"], gets the property type from every member.
Generic discriminated unions
Generics let one union pattern work with many data types:
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function parsePort(input: string): Result<number, string> {
const port = Number(input);
if (!Number.isInteger(port) || port < 0 || port > 65535) {
return { ok: false, error: `Invalid port: ${input}` };
}
return { ok: true, value: port };
}
const result = parsePort("8080");
if (result.ok) {
console.log(result.value); // number
} else {
console.log(result.error); // string
}The ok property narrows the result to exactly one member.
Common pitfalls
Object literals can widen a tag from a literal type to string:
const shape = { kind: "circle", radius: 2 };
// area(shape); // Error: kind is string
const fixed: Shape = { kind: "circle", radius: 2 };
const alsoFixed = { kind: "circle", radius: 2 } as const;Annotate the value or use as const. Also remember that TypeScript checks types at compile time. It does not verify JSON received from a network.
> callout note > Treat external data as unknown until your program validates its structure.
Custom type guards and external data
A custom type guard is a function whose return type uses value is SomeType:
function isShape(value: unknown): value is Shape {
if (typeof value !== "object" || value === null) return false;
const item = value as Record<string, unknown>;
switch (item.kind) {
case "circle":
return typeof item.radius === "number";
case "square":
return typeof item.size === "number";
case "rectangle":
return typeof item.width === "number" &&
typeof item.height === "number";
default:
return false;
}
}
const data: unknown = JSON.parse('{"kind":"square","size":3}');
if (isShape(data)) {
console.log(data.size); // safely narrowed to the square member
}Validate every required field before passing external data to code that expects the union.
Exercise
What type does Shape["kind"] produce?
Show answer
The union of all discriminant values: "circle" | "square" | "rectangle".