Variance Annotations On Type Parameters
Annotate type parameters with in and out to turn silent bivariance into compile errors, before a wrong-direction assignment fails only at runtime.
Code
// out:协变,T 只出现在输出位置(variance annotations)
interface Reader<out T> {
read(): T;
}
const numberReader: Reader<number> = { read: () => 42 };
// 协变方向:Reader<number> 可当作 Reader<unknown>
const wideReader: Reader<unknown> = numberReader;
console.log('reader:', wideReader.read());
// in:逆变,T 只出现在输入位置
interface Writer<in T> {
write(value: T): void;
}
const unknownWriter: Writer<unknown> = { write: (v) => console.log('writer got:', typeof v) };
// 逆变方向:能处理 unknown 的 writer 一定能处理 string
const stringWriter: Writer<string> = unknownWriter;
stringWriter.write('hello');
// 方法语法默认双变:没标注时错误方向的赋值静默通过,运行期才炸
interface LooseWriter<T> {
write(value: T): void;
}
const numberWriter: LooseWriter<number> = { write: (n) => console.log(n.toFixed(2)) };
const looseWriter: LooseWriter<unknown> = numberWriter;
try {
looseWriter.write('oops');
} catch (error) {
console.log('loose fails at runtime:', error instanceof TypeError);
}
// @ts-expect-error: in 标注下,Writer<string> 不能充当 Writer<unknown>
const badWriter: Writer<unknown> = stringWriter;
// @ts-expect-error: out 标注下,Reader<unknown> 不能收窄为 Reader<number>
const narrowReader: Reader<number> = wideReader;How it works
Reader<out T> is covariant: T appears only in output position (read(): T), so a Reader<number> may be used where Reader<unknown> is expected — the wideReader assignment in the file does exactly that. Writer<in T> is contravariant: T appears only in input position (write(value: T)), so the arrow points the other way — the Writer<unknown> value unknownWriter is assigned to the Writer<string> variable stringWriter, because anything that can write an unknown value can write a string.
The third interface, LooseWriter<T>, carries no annotation. Method syntax stays bivariant without one, so the wrong-direction assignment LooseWriter<unknown> = numberWriter compiles silently, and the failure only shows at runtime: looseWriter.write('oops') calls n.toFixed(2) on a string, and the TypeError is caught by the file’s try/catch, which prints loose fails at runtime: true.
The two @ts-expect-error directives at the end mark the assignments the variance annotations reject: badWriter tries to assign a Writer<string> to a Writer<unknown> slot, and narrowReader tries to narrow Reader<unknown> back to Reader<number> — under in/out both directions are compile errors instead of silent passes.
What to watch for
- There is no dependency tree here — the platform is the whole dependency.
Using it
Running the file prints labeled results such as reader:, writer got:, loose fails at runtime: — each operation’s effect is visible in the output.
Key statements
const numberReader: Reader<number> = { read: () => 42 };
Interactive Tools for This Topic
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do.
Report a problem with this exampleOpens a pre-filled issue on GitHub.