Sub topic 3
What you can access on a union before narrowing
A union type says a value is one of several types. The compiler does not know which one, so it only lets you use what is safe for every possibility. This chapter explains that rule, the types you get when you read a shared member, and the patterns that look like they should work but don't.
This chapter assumes you know basic type annotations, object types and type aliases, and function parameter and return types. It also assumes you have seen the A | B syntax. Narrowing, the technique that lifts these restrictions, is the next chapter's subject.
The rule: only members common to every union member
When you write pet.name on a value of type Cat | Dog, the compiler checks every member of the union. The access is allowed only if the property exists on all of them. If it is missing on even one member, the compiler reports an error, because at runtime the value might be that member.
type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };
function greet(pet: Cat | Dog): string {
return `Hello, ${pet.name}`; // OK: name exists on Cat and on Dog
}
function makeNoise(pet: Cat | Dog): void {
pet.meow(); // error
}The error on pet.meow() reads:
Property 'meow' does not exist on type 'Cat | Dog'.
Property 'meow' does not exist on type 'Dog'.The second line names the member that blocks the access. Read it first when you debug these errors: it tells you which union member lacks the property.
The accessible members of a union form the overlap of its members' members. This is the opposite of an intersection, where the result has everything from every member.
Why the compiler is strict about this
Suppose the compiler allowed pet.meow(). A Dog value would pass the type check and then fail at runtime with pet.meow is not a function. Rejecting the access moves that failure to compile time.
There is a subtlety. TypeScript uses structural typing, so a value of type Cat | Dog might have both meow and bark. For example, an object stored in a variable with both methods is assignable to either type. The compiler still cannot assume meow exists. A union describes what you may rely on, not everything the value has.
When a shared property has different types
A property can exist on every member but with a different type in each. The type you read is the union of those property types.
type Ticket = { id: number; seat: string };
type Booking = { id: string; date: Date };
function describeId(x: Ticket | Booking): string {
const id = x.id; // type: string | number
return String(id);
}The type of id is string | number, which is itself a union. You can only use the members that string and number have in common. This is the same rule applied again, one level down.
function broken(x: Ticket | Booking): string {
return x.id.toFixed(2); // error: 'toFixed' does not exist on type 'string'
}toFixed exists on number but not on string, so the call is rejected. To call it you have to narrow x.id first.
Shared methods on primitives and arrays
Unions of primitive types follow the same rule, using the members of the built-in types. string | number shares toString() and valueOf(), but not toUpperCase() or toFixed().
function show(value: string | number): string {
return value.toString(); // OK: both types have toString()
}A union of string literals is the easy case. Every member is a string, so every string method is available.
type Direction = "north" | "south" | "east" | "west";
function shout(d: Direction): string {
return d.toUpperCase(); // OK: each literal type is a string
}Methods that exist on every member with compatible signatures can also be called. The compiler combines the signatures and returns a union of the results.
function firstTwo(input: string | string[]): string | string[] {
console.log(input.length); // number: both have a numeric length
return input.slice(0, 2); // string | string[]
}Both string and string[] have length and slice(start, end). The call succeeds, and the result type is string | string[], because the compiler cannot know which branch ran. If the methods' parameters were incompatible, the call would fail. For instance, if one member's method needed a string argument and the other needed a number, no argument would satisfy both.
Optional properties and the union of undefined
A property that is optional on one member is still common to all members, as long as every member declares it. The read type then includes undefined.
type Guest = { name: string; age?: number };
type Member = { name: string; age: number };
function ageOf(p: Guest | Member): number | undefined {
return p.age; // number | undefined
}Compare this with a property that one member does not declare at all. That case is an error, not a union with undefined.
type A = { a: string };
type B = { b: number };
function readA(x: A | B): void {
console.log(x.a); // error: Property 'a' does not exist on type 'A | B'.
}Making a missing property readable with an optional undefined
Sometimes you want to read a property from every member without narrowing. You can declare the missing property on the other members as optional with type undefined. Then the property is common to all members.
type Success = { ok: true; value: string; error?: undefined };
type Failure = { ok: false; error: string; value?: undefined };
function show(r: Success | Failure): string | undefined {
return r.value ?? r.error; // allowed: both members declare both properties
}This is a trade-off. You can read both properties directly, but you have to repeat the extra declarations on each member. The compiler also no longer proves that error is a string after you check r.ok. That relationship is better expressed with a discriminated union, covered in a later chapter. Use this pattern only when reading a value that may be absent is exactly what you want.
Null and undefined in a union
string | null is a union like any other. null has no properties, so under strictNullChecks (part of strict) no property access passes.
function length(s: string | null): number {
return s.length; // error: 's' is possibly 'null'.
}The message differs from the "does not exist" error, but the cause is identical. The compiler checks that length exists on string and on null, and it does not exist on null. Optional chaining (s?.length) handles this case. It narrows away null and undefined and produces number | undefined.
A summary of the rules
| Expression | Value type | Allowed? | Why | Column | Column |
|---|---|---|---|---|---|
| `pet.name` | `Cat \ | Dog` | Yes | `name` is on both members | |
| `pet.meow()` | `Cat \ | Dog` | No | `Dog` has no `meow` | |
| `x.id` | `{ id: number } \ | { id: string }` | Yes, type `string \ | number` | The property types are unioned |
| `x.id.toFixed()` | same as above | No | `string` has no `toFixed` | ||
| `v.toString()` | `string \ | number` | Yes | Both types have `toString` | |
| `s.length` | `string \ | null` | No | `null` has no members | |
| `s?.length` | `string \ | null` | Yes, type `number \ | undefined` | Optional chaining skips `null` |
Do not silence the error with an assertion
You can force the access with a type assertion, such as (pet as Cat).meow(). This tells the compiler to stop checking, and the runtime failure for a Dog returns.
Common mistakes
- Expecting union members to behave like an intersection. A beginner often reads
Cat | Dogas "has the members of both". That isCat & Dog. A union has fewer accessible members than any of its parts. - Reading the first error line only. The nested line, such as "Property 'meow' does not exist on type 'Dog'", names the member that blocks the access.
- Forgetting that shared properties can have different types.
x.idcompiles, but the result isstring | number, so calling number-only methods on it fails. - Declaring a property on only one member and reading it everywhere. Add the property as
?: undefinedon the others, or restructure into a discriminated union. - Assuming a union value has exactly one member's shape at runtime. Structural typing allows values that satisfy several members. Do not use the absence of a property in the type as proof of its absence in the object.
Checking your understanding
Exercise
Given type Square = { side: number; color: string } and type Circle = { radius: number; color: string }, which of these compile for a parameter s: Square | Circle: s.color, s.side, s.color.toUpperCase()? Explain each.
Show answer
s.color compiles because both members declare color. s.color.toUpperCase() also compiles because color is string on both, so the read type is string. s.side does not compile because Circle has no side property; the error names Circle.
Exercise
What is the type of x.id when x is { id: number } | { id: string }, and why does x.id.toFixed(2) fail? Name one way to make the call valid.
Show answer
The type is string | number, the union of the two property types. toFixed exists only on number, and the value might be a string, so the call fails. Narrow first, for example if (typeof x.id === "number") { x.id.toFixed(2); }.