A subscription callback is a consumer of a payload. If the channel promises only title, the callback cannot require subtitle as well. The caller may publish a title-only record. This is the callback safety rule from intermediate, now applied to a public library.
Use function-valued properties in the contract, such as subscribe: (listener: Listener<T>) => () => void. Under strict checking they participate in the parameter compatibility rules we want. Read the syntax as a property named subscribe whose value is a function; its parameter is another function, and its result is a cleanup function. This explicit property form matters for a public library. Function-typed properties are checked contravariantly in their parameters: a callback may accept less than the channel sends, never more. Method declarations (handle(book: Book): void) are checked bivariantly even under strict mode, so either direction is accepted, including the unsafe one. The lab below shows the difference.
A returned cleanup function gives ownership to the subscriber. Calling it twice should be harmless. Two registrations of the same callback must still be independent if that is the documented API. Those are runtime rules, not consequences of the generic T.
Today's small connection owns one callback and an active flag. Its cleanup actually prevents future delivery. The checkpoint grows it into independent subscriptions, and Day 5 tightens the return contract and adds disposal. Read the contract and behavior separately so a type annotation never substitutes for cleanup code.
Predict, check, and run
Write the output before running. Use Check types first, then Check & run. Types disappear at runtime: explain both what the compiler checks and what the code actually does. Each editor is an independent ES module; await asynchronous work explicitly.
type Listener<T> = (value: T) => void;
function connect<T>(listener: Listener<T>) {
let active = true;
return {
publish(value: T): void {
if (active) {
listener(value);
}
},
cleanup(): void {
active = false;
}
};
}
const connection = connect<{ title: string }>(book => {
console.log(book.title);
});
connection.publish({ title: "Types" });
connection.cleanup();
connection.cleanup();
connection.publish({ title: "Hidden" });Enable JavaScript to edit and type-check this example.
Check your prediction
TypesRead the compiler error
Predict the rejected relationship before checking. Read the real diagnostic and its source location; fix the contract or the value instead of hiding it with an assertion.
type Book = { title: string };
type RichBook = {
title: string;
subtitle: string;
};
function subscribe(listener: (book: Book) => void): void {}
subscribe((book: RichBook) => {
console.log(book.subtitle);
});Enable JavaScript to edit and type-check this example.
Check your diagnosis
Read the message from the bottom: Property 'subtitle' is missing in type 'Book' but required in type 'RichBook'. The line above, Types of parameters 'book' and 'book' are incompatible, places the failure in the callback's parameter: the channel will call it with a Book, which may have no subtitle.
A subscriber promised Book cannot require the extra subtitle. Accept the public payload contract and only read guaranteed fields.
A callback consumes the promised payload
A subscriber may use only the fields guaranteed by the channel. Accepting a broader input is safe; demanding a richer record than the channel promises is not. Trace the actual value the publisher can send before judging a callback by its name or current fixture.
Return values are another independent part of the contract. Today’s familiar void callback permits ignored returns; Day 5 tightens it for a synchronous channel. Do not assume parameter safety also proves settlement or cleanup behavior.
type Book = { title: string };
function announce(book: Book, listener: (value: Book) => void): void {
listener(book);
}
const richer = { title: "Types", pages: 120 };
announce(richer, book => {
console.log(book.title);
});Enable JavaScript to edit and type-check this example.
Check your prediction
TypesThe callback accepts the public Book contract even though this one object is richer. A future publisher may provide no pages field, so the listener must not require it.
let active = true;
function publish(value: string, listener: (value: string) => void): void {
if (active) {
listener(value);
}
}
const listener = (value: string) => {
console.log(value);
};
publish("Types", listener);
active = false;
publish("Hidden", listener);Enable JavaScript to edit and type-check this example.
Check your prediction
TypesThe active flag implements behavior outside the function type. A cleanup return signature alone would not make the second delivery disappear.
Method shorthand lets an unsafe listener through
The two contracts below describe the same listener object. One uses a method declaration and one a function-valued property. The listener needs pages, which the channel never promises.
type Book = { title: string };
type DetailedBook = { title: string; pages: number };
type MethodListener = { handle(book: Book): void };
type PropertyListener = { handle: (book: Book) => void };
const needsPages = {
handle: (book: DetailedBook) => console.log(book.pages.toFixed(0))
};
const viaMethod: MethodListener = needsPages;
const viaProperty: PropertyListener = needsPages;
viaMethod.handle({ title: "Types" });
viaProperty.handle({ title: "Types" });Enable JavaScript to edit and type-check this example.
Check your diagnosis
There is only one error, and that is the lesson. The key line is TS2322: Type '{ handle: (book: DetailedBook) => void; }' is not assignable to type 'PropertyListener'. Read down to Types of parameters 'book' and 'book' are incompatible: the property form compared the parameters in the safe direction and found that Book lacks pages. The viaMethod line has the same mismatch and no error, because method parameters are bivariant. Delete the viaProperty lines and the program compiles, then crashes at runtime with TypeError: Cannot read properties of undefined (reading 'toFixed').
The fix is in the listener, not the contract: make it accept the promised Book and use only title.
type Book = { title: string };
type MethodListener = { handle(book: Book): void };
type PropertyListener = { handle: (book: Book) => void };
const titleOnly = {
handle: (book: Book) => console.log(book.title)
};
const viaMethod: MethodListener = titleOnly;
const viaProperty: PropertyListener = titleOnly;
viaMethod.handle({ title: "Types" });
viaProperty.handle({ title: "Generics" });Enable JavaScript to edit and type-check this example.
Check your prediction
Types
GenericsWith an honest listener both forms work. The difference is only in what they let through by mistake, which is why the public contracts in this course use property form.
Try the rule on new inputs
Try a callback accepting only the guaranteed shape and one requiring an extra field. Then write an observable cleanup test. Keep parameter compatibility, return behavior and lifecycle as three separate questions.
Trace the contract before building
A callback contract includes when it runs, which argument it receives, and how its result is handled. Parameter and return annotations cover only part of that agreement. A synchronous listener API must decide what to do about callbacks that start asynchronous work, since their later failures are outside an ordinary synchronous try/catch.
Read the accepted signature and then trace dispatch step by step. Test listener order, a throwing listener, and removal during dispatch according to the documented policy. Avoid claiming the compiler enforces temporal behavior: the implementation and runtime tests must establish the lifecycle rules even when every callback has the correct static type.
Build it yourself
Callback Contracts: practice
Write mapListener<A, B>(convert, listener). It returns a new listener for A values that converts each value with convert and passes the result to listener, a listener for B values. Use it to turn a string listener into a Book listener that logs the upper-case title. Call it with a DetailedBook { title: "Types", pages: 120 } and with { title: "Generics" }; print TYPES then GENERICS. Then try a listener that expects a number and read the error.
type Book = { title: string };
type DetailedBook = { title: string; pages: number };
// Write mapListener, then build and call the Book listener.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
Follow the data: an A arrives, convert turns it into a B, and the B goes to the listener. So convert consumes A and produces B, and the listener consumes B.
Hint 2: a first step
The signature has three function types: convert: (value: A) => B, listener: (value: B) => void, and the returned (value: A) => void. Annotate the converter's parameter as Book so A is inferred from it.
Show one solution
type Book = { title: string };
type DetailedBook = { title: string; pages: number };
function mapListener<A, B>(
convert: (value: A) => B,
listener: (value: B) => void
): (value: A) => void {
return value => listener(convert(value));
}
const onBook = mapListener(
(book: Book) => book.title.toUpperCase(),
title => console.log(title)
);
const detailed: DetailedBook = { title: "Types", pages: 120 };
onBook(detailed);
onBook({ title: "Generics" });Enable JavaScript to edit and type-check this example.
TYPES
GENERICSThe returned listener accepts a Book, so a richer DetailedBook is fine: a listener may receive more than it needs. B is inferred as string from the converter's result, which gives title its type without an annotation. Replacing the second argument with (count: number) => ... fails with TS2345: the converter produces a string where a number is now required. The adapter only connects the directions; it cannot make a listener that wants more data safe.
Change it and test it
In the method-versus-property lab, give the listener a parameter of { title: string | number } and check both forms; explain why a wider parameter is safe. Then pass mapListener a converter annotated with DetailedBook and call the result with { title: "Generics" }. Explain why accepting fewer guarantees is safe while demanding more is not.
Completion is saved in this browser only. It does not measure mastery.