Assignability and freshness
A Relay worker takes a Job, retries it, and hands a copy to an audit log typed Readonly<Job>.
Someone writes a helper bumpAttempts(job: Job) and passes the audit copy to it. It compiles, and
the “read-only” record changes. In the same week, retry({ retires: 3 }) is rejected but
retry(options) with the same typo stored in a variable is accepted. Both are the checker working
as specified. This lesson reads the specification: what assignable means, one rule at a time.
Everything in the checker is a relation between two types. S is assignable to T when a value of
type S may be stored where T is expected. M1 showed the common cases. Here are
the rules underneath, including the places where they are looser than you would guess.
Members, one by one
Section titled “Members, one by one”For object types, S is assignable to T when every property of T exists in S with an
assignable type. Extra properties in S are fine, and a required property cannot be missing:
type Job = { id: string; attempts: number }type Audit = { id: string }
declare const job: Jobconst audit: Audit = job // extra `attempts` is fine// @ts-expect-error: property 'attempts' is missingconst back: Job = auditOptionality is part of the comparison. A required property satisfies an optional one, never the
other way. With exactOptionalPropertyTypes (on in Relay), tags?: string[] also means “absent”,
not “present and undefined”:
type Stored = { id: string; tags?: string[] }type Strict = { id: string; tags: string[] | undefined }
declare const stored: Stored// @ts-expect-error: 'tags' is optional in Stored but required in Strictconst s: Strict = stored
declare const strict: Strict// @ts-expect-error: 'string[] | undefined' is not assignable under exactOptionalPropertyTypesconst t: Stored = strictreadonly is not part of the relation
Section titled “readonly is not part of the relation”The assignability check ignores readonly on properties. A readonly property is assignable to a
mutable one and back:
type Job = { id: string; attempts: number }
declare const audit: Readonly<Job>const mutable: Job = audit // accepted: no errormutable.attempts += 1 // and now the "readonly" record changesreadonly only blocks writes through that particular reference. The reason is practical: a
{ readonly id: string } parameter is how a function says “I will not write”, so rejecting it for
a mutable argument would make readonly unusable. The cost is that it cannot say “nobody writes”.
Arrays are the exception: readonly string[] is a different type with no push, and is not
assignable to string[]:
declare const names: readonly string[]// @ts-expect-error: 'readonly string[]' is 'readonly' and cannot be assigned to the mutable typeconst copy: string[] = namesIf a read-only value must never reach a mutating function, make the two types incompatible with a brand. The exercise does exactly that. M4 brands covers the technique.
Freshness: excess property checks
Section titled “Freshness: excess property checks”M1 says extra keys in an object literal are an error. The precise rule is narrower. An object literal expression has a fresh type. Assigning a fresh type to a target checks for excess properties: any property the target does not declare is an error. The moment the literal is stored in a variable, its type is widened to a regular, non-fresh object type and the check no longer applies:
type RetryOptions = { maxAttempts?: number; delayMs?: number }declare function retry(options: RetryOptions): void
// @ts-expect-error: 'retires' does not exist in type 'RetryOptions'retry({ maxAttempts: 3, retires: 3 })
const options = { maxAttempts: 3, retires: 3 }retry(options) // accepted: `options` is no longer freshFreshness is a property of the expression, not of the value. It is lost by assignment to a variable, and it does not help when the literal is passed to a generic parameter whose type parameter captures it:
type Handlers = { "job.queued": (id: string) => void }
declare function register<H extends Handlers>(handlers: H): H
register({ "job.queued": () => {}, "job.queud": () => {}, // accepted: H is inferred as the literal's own type})Here H is the argument’s type, so the argument is trivially assignable to it. The target for the
excess check is H, not Handlers. To close this hole, make the extra keys’ type never:
type Handlers = { "job.queued": (id: string) => void }type NoExtraKeys<H> = Record<Exclude<keyof H, keyof Handlers>, never>
declare function register<H extends Handlers>(handlers: H & NoExtraKeys<H>): H
register({ "job.queued": () => {} })// @ts-expect-error: '() => void' is not assignable to 'never'register({ "job.queued": () => {}, "job.queud": () => {} })
const table = { "job.queued": () => {}, "job.queud": () => {} }// @ts-expect-error: the check now works for non-fresh values tooregister(table)Exclude<keyof H, keyof Handlers> is the set of keys H has beyond Handlers. If there are none,
the record is {} and imposes nothing. Otherwise each extra key must have type never, which no
value has.
Weak type detection
Section titled “Weak type detection”A weak type is an object type whose properties are all optional. Without a special rule, nearly everything would be assignable to it, because no required property can be missing. Since TypeScript 2.4, assigning to a weak type is an error when the source has properties but shares none with the target:
type RetryOptions = { maxAttempts?: number; delayMs?: number }declare function retry(options: RetryOptions): void
const typo = { retires: 3 }// @ts-expect-error: type '{ retires: number; }' has no properties in commonretry(typo)
const mixed = { maxAttempts: 3, retires: 3 }retry(mixed) // one shared property is enough: the rule is only about zero overlapretry({}) // the empty object has no properties, so the rule does not applyTwo limits. One shared property disables the check, so it catches only the total miss. And {}
passes, which is rarely what an options type means. If “at least one option” is the contract,
state it in the type:
type RetryOptions = | { maxAttempts: number; delayMs?: number } | { maxAttempts?: number; delayMs: number }
declare function retry(options: RetryOptions): void
retry({ delayMs: 50 })// @ts-expect-error: an empty object matches neither memberretry({})The comparable relation
Section titled “The comparable relation”Assignability is not the only relation. ===, switch/case and type assertions use the
comparable relation. It is more permissive in one specific way: for unions, a single member
matching is enough, in either direction. That is why you can compare a string to a literal, and
why a literal that can never match is an error:
declare const status: "queued" | "running"declare const text: string
if (status === "queued") {}if (text === "queued") {}// @ts-expect-error: no overlap between '"queued" | "running"' and '"done"'if (status === "done") {}// @ts-expect-error: no overlap between 'string' and 'number'if (text === 1) {}A type assertion x as T is allowed when T is comparable to the type of x, or the other way
round. T may be a narrower type, which is why as can lie, and it can also be a wider one:
declare const text: stringdeclare const status: "queued" | "running"
text as "queued" // narrowing: "queued" is comparable to stringstatus as string // widening: also allowed// @ts-expect-error: 'string' and 'number' are not comparabletext as number// @ts-expect-error: 'number' and '"queued"' are not comparable1 as "queued"Only an unrelated pair needs as unknown as T. Lesson 5 catalogs what that
costs.
{}, object and unknown
Section titled “{}, object and unknown”Three top-ish types that look alike:
unknownaccepts every value, includingnullandundefined, and allows nothing on read.{}accepts every value exceptnullandundefined. Primitives are assignable to it, and you can readtoStringand the other members ofObject.objectaccepts every non-primitive value.
const a: {} = 1const b: {} = "relay"// @ts-expect-error: null is not assignable to '{}'const c: {} = null// @ts-expect-error: a number is not assignable to 'object'const d: object = 1const e: object = []const f: unknown = nullPrefer unknown for “any value, check before use”. {} appears in real code as “anything but
nullish”, usually in a generic constraint: T extends {}.
Index signatures against named properties
Section titled “Index signatures against named properties”A type with an index signature promises that every string key has that type. Named properties must be compatible with it, and an object type is assignable to a signature only if the source can prove it. The proof depends on how the type was written:
type Counts = { [source: string]: number }
// @ts-expect-error: property 'label' of type 'string' is not assignable to the index typetype Bad = { [source: string]: number; label: string }
type ByType = { github: number }interface ByInterface { github: number}
declare const fromType: ByTypedeclare const fromInterface: ByInterface
const ok: Counts = fromType // type aliases get an implicit index signature// @ts-expect-error: interfaces do not, because they can be merged and extended elsewhereconst rejected: Counts = fromInterfaceA type alias for an object literal type is closed: the checker knows all its keys, so it can check
them against the signature. An interface is open to declaration merging, so it refuses. Relay’s
Record<string, number> helpers behave the same way.
Function assignability
Section titled “Function assignability”For (a: A) => R to be assignable to (b: B) => S, parameters are compared the other way round
(contravariantly) and results the same way (covariantly). Variance explained why.
Three rules specific to functions:
type Handler = (id: string) => void
const fewer: Handler = () => {}const fewerParams: Handler = (id: string) => {}// @ts-expect-error: the source requires two arguments, the target supplies oneconst more: Handler = (id: string, retries: number) => {}const optional: Handler = (id: string, retries?: number) => {}
const ignoresResult: Handler = () => 42- A function may declare fewer parameters. Callers pass extras and they are ignored.
- It may not require more: an optional extra parameter is fine.
- A target returning
voidaccepts a source returning anything. The value is discarded, which is howitems.forEach((x) => set.add(x))compiles.
Parameter checking is strict only for function-type syntax. Under strictFunctionTypes, methods
declared with method syntax stay bivariant so that built-in types like Array<T> keep working:
interface Animal { name: string }interface Dog extends Animal { bark(): void }
type PropertyStyle = { handle: (animal: Animal) => void }type MethodStyle = { handle(animal: Animal): void }
declare const dogHandler: (dog: Dog) => void
// @ts-expect-error: property syntax is checked contravariantlyconst p: PropertyStyle = { handle: dogHandler }const m: MethodStyle = { handle: dogHandler } // accepted: method syntax is bivariantAt runtime m.handle receives any Animal, and dogHandler calls bark() on it. For handler
tables and callbacks in Relay’s public types, prefer property syntax.
Exercise
Section titled “Exercise”Relay passes jobs, retry options and handler tables between modules, and three misuses compile.
Change the types so each one is rejected, and finish retryDelay. The tests contain
@ts-expect-error lines that fail while the types are too loose.
- Object assignability checks members: required properties must exist, optional ones may be
missing, extras are fine.
readonlyis ignored, except forreadonly T[]. - Excess property checks apply only to fresh object literals. A variable, a generic capture or an assertion removes freshness.
- Weak type detection rejects a source with zero overlap with an all-optional target, nothing more.
===,caseandasuse the comparable relation: overlap in either direction is enough.{}is non-nullish,objectis non-primitive,unknownis everything.- Type aliases are assignable to index signatures, interfaces are not.
- Fewer parameters is fine, more is not,
voidreturns discard values, and method syntax is bivariant.
Further reading
Section titled “Further reading”- TypeScript 2.4: Weak Type Detection: the all-optional-properties check.
- Type Compatibility: the official rules for functions, optional parameters and assignment.
- TypeScript 2.6: Strict function types: parameter contravariance and why methods are excluded.