Variance
Relay’s event bus has handlers for JobEvent, and some code that only cares about JobStarted.
Questions come up at every boundary. Can I pass a list of JobStarted where a list of JobEvent is
expected? Can a handler for any event stand in for a handler for started events? The answers differ,
and a wrong “yes” is a runtime crash that the compiler waved through.
Two types here. JobStarted is a subtype of JobEvent: every JobStarted is a JobEvent, not
the other way around. Variance is how that relation carries over to Box<JobStarted> and
Box<JobEvent>.
interface JobStarted { readonly _tag: "JobStarted" readonly jobId: string readonly worker: string}interface JobFailed { readonly _tag: "JobFailed" readonly jobId: string readonly reason: string}type JobEvent = JobStarted | JobFailed
declare const started: JobStartedconst event: JobEvent = started // fine: a subtype goes where a supertype is expectedCovariance: producers
Section titled “Covariance: producers”If Box<T> only gives out a T, then Box<JobStarted> is a Box<JobEvent>. Whoever reads from
it expects some JobEvent and gets a JobStarted, which is one. The direction is preserved, so
this is covariant:
type JobStarted = { readonly _tag: "JobStarted"; readonly jobId: string }type JobEvent = JobStarted | { readonly _tag: "JobFailed"; readonly jobId: string }
declare const started: ReadonlyArray<JobStarted>const events: ReadonlyArray<JobEvent> = started
declare const next: () => JobStartedconst nextEvent: () => JobEvent = next // return types are covariant tooRead-only arrays, return types and readonly properties are all outputs.
Contravariance: consumers
Section titled “Contravariance: consumers”If Handler<T> only takes in a T, the direction flips. A handler for any JobEvent can serve
where a handler for JobStarted is needed, because every JobStarted it receives is an event it
can handle. The reverse is a bug: a handler that reads e.worker receives a JobFailed.
type JobStarted = { readonly _tag: "JobStarted"; readonly worker: string }type JobEvent = JobStarted | { readonly _tag: "JobFailed"; readonly reason: string }
declare const onEvent: (e: JobEvent) => voiddeclare const onStarted: (e: JobStarted) => void
const forStarted: (e: JobStarted) => void = onEvent // fine// @ts-expect-error: 'JobEvent' is not assignable to 'JobStarted'const forAny: (e: JobEvent) => void = onStartedThis is contravariant: Handler<JobEvent> is a Handler<JobStarted>, not the other way. It is
checked this way under strictFunctionTypes, which is part of strict, so Relay has it on.
Both directions: invariance
Section titled “Both directions: invariance”A type that both reads and writes a T can’t be safely substituted in either direction. A
mutable array is that type: push takes a T and indexing gives one out. A sound check would
reject both assignments. TypeScript doesn’t, for arrays:
type JobStarted = { readonly _tag: "JobStarted"; readonly worker: string }type JobFailed = { readonly _tag: "JobFailed"; readonly reason: string }type JobEvent = JobStarted | JobFailed
const started: JobStarted[] = [{ _tag: "JobStarted", worker: "w1" }]const events: JobEvent[] = started // compiles: arrays are checked covariantlyevents.push({ _tag: "JobFailed", reason: "oom" })
started[1]?.worker.toUpperCase() // compiles; at runtime started[1] is a JobFailed, so worker is undefined: TypeErrorevents and started are the same array. Through events you pushed a JobFailed, and through
started the code still believes every element is a JobStarted. TypeScript allows this on purpose:
rejecting it would break too much everyday code. The fix is in your hands: accept readonly T[]
when you only read. Then the covariant assignment is sound, and the push on the alias doesn’t
compile:
type JobStarted = { readonly _tag: "JobStarted"; readonly worker: string }type JobFailed = { readonly _tag: "JobFailed"; readonly reason: string }type JobEvent = JobStarted | JobFailed
declare const started: JobStarted[]const events: readonly JobEvent[] = started// @ts-expect-error: Property 'push' does not exist on type 'readonly JobEvent[]'events.push({ _tag: "JobFailed", reason: "oom" })Method syntax is bivariant
Section titled “Method syntax is bivariant”There is a second leniency, and it is easy to hit. Parameters of methods are checked bivariantly, meaning in either direction. Only function-typed properties get the strict check:
type JobStarted = { readonly _tag: "JobStarted"; readonly worker: string }type JobEvent = JobStarted | { readonly _tag: "JobFailed"; readonly reason: string }
interface MethodHandlers { onEvent(e: JobEvent): void}interface PropertyHandlers { readonly onEvent: (e: JobEvent) => void}
// Compiles, and its handler crashes on JobFailed:const loose: MethodHandlers = { onEvent: (e: JobStarted) => console.log(e.worker) }
// @ts-expect-error: 'JobEvent' is not assignable to 'JobStarted'const strict: PropertyHandlers = { onEvent: (e: JobStarted) => console.log(e.worker) }The exception exists so that old patterns like Array<T> stay assignable. For a callback slot
that you design, use property syntax: onEvent: (e: JobEvent) => void. Use method syntax for
real methods on classes and for objects whose members are not swapped out.
in and out annotations
Section titled “in and out annotations”TypeScript works variance out from how T is used. Since 4.7 you can also state it on the
parameter. out T means covariant (T only comes out), in T means contravariant (T only goes in):
interface Source<out T> { readonly next: () => T}interface Sink<in T> { readonly push: (value: T) => void}
// @ts-expect-error: Type 'T' is not assignable to type 'T' (T is used in an input position)interface BadSource<out T> { readonly push: (value: T) => void}The annotation does two jobs. It is documentation: a reader sees the direction without
analyzing the body. And it is checked: if the body uses T the wrong way, the declaration
fails, as BadSource does. It can also make checks faster on big generic types. In our tests, with method syntax
it also overrides the lenient rule, so Sink<in T> rejects Sink<JobStarted> as a
Sink<JobEvent> even when push is written as a method.
Exercise
Section titled “Exercise”Relay’s handler registry lets three unsafe things through: a narrow handler, a mutable alias of a
list, and a Sink with no stated direction. The tests contain assignments that must fail once
the types are right.
JobStartedis a subtype ofJobEvent. Variance says whetherBox<JobStarted>is aBox<JobEvent>.- Producers (
readonly T[], return types) are covariant. Consumers (parameters) are contravariant, understrictFunctionTypes. Read and write is invariant. - Mutable arrays are checked covariantly even though that is unsound. Use
readonly T[]for inputs. - Method syntax is bivariant. Use property syntax
f: (x: T) => voidfor callback slots. in Tandout Tdocument the direction and make the compiler check it.
Further reading
Section titled “Further reading”- TypeScript 4.7 release notes:
inandoutvariance annotations. - Handbook: More on Functions: parameter bivariance.