Skip to content

Variance in service interfaces

Relay’s worker now has a job store and an event bus, both passed in as ports (lesson 1). Soon there are two kinds of record: a plain Job, and a QueuedJob that also has a queuedAt time. The question from M3 variance comes back at service level. Can a Repo<QueuedJob> be passed where a Repo<Job> is wanted? A wrong “yes” means a plain job lands in a store whose readers expect queuedAt.

M3 covered the rules for values and callbacks. This lesson applies them to the interfaces you write for services, where the cost of a lenient check is a bug that shows up in production, not in a test.

Method syntax lets the unsafe wiring through

Section titled “Method syntax lets the unsafe wiring through”

A store with get and put, written the way most people write interfaces:

interface Job {
readonly id: string
readonly kind: string
}
interface QueuedJob extends Job {
readonly queuedAt: number
}
interface Repo<T> {
get(id: string): T | undefined
put(item: T): void
}
declare const queued: Repo<QueuedJob>
const jobs: Repo<Job> = queued // compiles
jobs.put({ id: "j1", kind: "email" }) // a plain Job goes into the QueuedJob store
queued.get("j1")?.queuedAt.toFixed() // TypeError at runtime: queuedAt is undefined

put(item: T) is a method, and method parameters are checked in both directions. The compiler saw a QueuedJob parameter against a Job parameter, found they are related, and accepted it. In a service interface that is the wrong call every time.

Write each capability as a property with a function type, and the check becomes strict:

interface Job {
readonly id: string
readonly kind: string
}
interface QueuedJob extends Job {
readonly queuedAt: number
}
interface Repo<T> {
readonly get: (id: string) => T | undefined
readonly put: (item: T) => void
}
declare const queued: Repo<QueuedJob>
// @ts-expect-error: Repo<QueuedJob> is not assignable to Repo<Job>
const jobs: Repo<Job> = queued

This is the rule from M3 applied on purpose: ports are swapped out (a fake in tests, a real store in production), so they get property syntax. readonly also stops anyone replacing put on a shared object.

A store that reads and writes is invariant

Section titled “A store that reads and writes is invariant”

Repo<T> uses T in an output (get) and an input (put), so it is invariant: Repo<QueuedJob> is not a Repo<Job> and Repo<Job> is not a Repo<QueuedJob>. That is correct. Two things to take from it:

  • Do not fight it with casts. The compiler is right that the two stores hold different things.
  • Do not give a function a whole Repo<T> when it uses half of it. That is what makes the type too rigid.

Give each capability its own interface, state the direction, and rebuild the full store from the halves:

interface Job {
readonly id: string
readonly kind: string
}
interface QueuedJob extends Job {
readonly queuedAt: number
}
interface Reader<out T> {
readonly get: (id: string) => T | undefined
}
interface Writer<in T> {
readonly put: (item: T) => void
}
interface Repo<T> extends Reader<T>, Writer<T> {}
declare const readQueued: Reader<QueuedJob>
declare const writeJob: Writer<Job>
declare const repoQueued: Repo<QueuedJob>
const readAny: Reader<Job> = readQueued // reads of a subtype are reads of the supertype
const writeQueued: Writer<QueuedJob> = writeJob // a writer for any Job can write a QueuedJob
// @ts-expect-error: a Reader<Job> may return a Job with no queuedAt
const readOnlyQueued: Reader<QueuedJob> = readAny
// @ts-expect-error: a Writer<QueuedJob> cannot accept every Job
const writeAny: Writer<Job> = writeQueued
const half: Reader<Job> = repoQueued // the full store, used through its read half

Repo<T> is still invariant, and nobody needs it to be anything else. The functions that use it ask for halves, so they accept more:

interface Job {
readonly id: string
readonly kind: string
}
interface QueuedJob extends Job {
readonly queuedAt: number
}
interface Reader<out T> {
readonly get: (id: string) => T | undefined
}
interface Writer<in T> {
readonly put: (item: T) => void
}
function markQueued(reader: Reader<Job>, writer: Writer<QueuedJob>, id: string, at: number): boolean {
const job = reader.get(id)
if (job === undefined) return false
writer.put({ ...job, queuedAt: at })
return true
}
declare const inbox: Reader<Job>
declare const archive: Writer<Job> // an audit log that stores any Job
declare const queue: Writer<QueuedJob>
markQueued(inbox, queue, "j1", 500)
markQueued(inbox, archive, "j1", 500) // fine: the audit log accepts a QueuedJob too

markQueued reads plain jobs and writes queued ones. A Repo<Job> and a Repo<QueuedJob> both fit, and so do the narrow fakes a test builds. This is the same idea as lesson 1: ask for exactly what you use, here applied to the type parameter.

An event bus has the same split. Publishing takes events in, so it is contravariant. Subscribing takes a handler, and a handler takes events in. The input of an input flips back, so subscribing is covariant:

interface JobStarted {
readonly _tag: "JobStarted"
readonly jobId: string
}
interface JobFailed {
readonly _tag: "JobFailed"
readonly jobId: string
readonly reason: string
}
type JobEvent = JobStarted | JobFailed
interface Publisher<in E> {
readonly publish: (event: E) => void
}
interface Events<out E> {
readonly subscribe: (handler: (event: E) => void) => void
}
declare const publishAny: Publisher<JobEvent>
declare const publishStarted: Publisher<JobStarted>
declare const startedEvents: Events<JobStarted>
declare const allEvents: Events<JobEvent>
const toStarted: Publisher<JobStarted> = publishAny // fine
// @ts-expect-error: a Publisher<JobStarted> cannot accept a JobFailed
const toAny: Publisher<JobEvent> = publishStarted
const fromStarted: Events<JobEvent> = startedEvents // fine: every started event is an event
// @ts-expect-error: an Events<JobEvent> may deliver a JobFailed
const fromAny: Events<JobStarted> = allEvents

A function that forwards events shows why this matters:

interface Publisher<in E> {
readonly publish: (event: E) => void
}
interface Events<out E> {
readonly subscribe: (handler: (event: E) => void) => void
}
interface JobStarted {
readonly _tag: "JobStarted"
readonly jobId: string
}
interface JobFailed {
readonly _tag: "JobFailed"
readonly jobId: string
readonly reason: string
}
function forward<E>(from: Events<E>, to: Publisher<E>): void {
from.subscribe((event) => to.publish(event))
}
declare const started: Events<JobStarted>
declare const audit: Publisher<JobStarted | JobFailed>
forward(started, audit) // E is JobStarted: the audit publisher accepts it and more

Relay can send started events to an audit log that records every kind of event, and the types agree because Events is out and Publisher is in.

The messages are long, but they follow one shape. Here is the message for the Repo<QueuedJob> to Repo<Job> assignment earlier:

error TS2322: Type 'Repo<QueuedJob>' is not assignable to type 'Repo<Job>'.
Types of property 'put' are incompatible.
Type '(item: QueuedJob) => void' is not assignable to type '(item: Job) => void'.
Types of parameters 'item' and 'item' are incompatible.
Property 'queuedAt' is missing in type 'Job' but required in type 'QueuedJob'.

Read it from the bottom up. The last line is the actual fact: a Job has no queuedAt. The line above says it happened at a parameter (item), which means the position is an input. The put line names the member. So Repo fails because put takes a QueuedJob and would receive a Job. When the failing member is a parameter, expect contravariance. When it is a return type, covariance. When the message names the same type argument going both ways, the interface is invariant and needs splitting.

For comparison, the same mistake on a reader gives a short message, because there is no parameter in it:

error TS2322: Type 'Reader<Job>' is not assignable to type 'Reader<QueuedJob>'.
Property 'queuedAt' is missing in type 'Job' but required in type 'QueuedJob'.

Do not split every interface. If one function uses both halves of a store and nothing is ever swapped, a plain Repo<T> is clearer. Split when callers have different needs: a report reads, an importer writes, a test only fakes one side. Keep method syntax for real methods on classes you construct and never substitute, and skip in/out on generic types that are only ever used with one argument.

Relay’s job store and event bus are single interfaces with method syntax, so unsafe wiring compiles and markQueued demands two full repos. Split them into readers and writers, state the direction, and finish the bus. The tests include assignments that must stop compiling.

  • Write service capabilities as properties with function types. Method syntax is bivariant and accepts unsafe wiring.
  • A type that reads and writes T is invariant. Repo<QueuedJob> is not a Repo<Job>, and that is correct.
  • Split it: Reader<out T> and Writer<in T>, then Repo<T> extends Reader<T>, Writer<T>. Functions ask for the halves.
  • Publishing is contravariant (in). Subscribing takes a handler, so it flips back to covariant (out).
  • Read a variance error from the bottom: the parameter or return type that disagrees tells you the direction.