What is the Variance annotation in TypeScript 4.7?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

TypeScript 4.7 introduced explicit variance annotations with in and out modifiers on generic type parameters, giving you direct control over how the type-checker handles subtype relationships. out T marks T as covariant — T only appears in output positions (return types): interface Getter<out T> { get(): T; }. in T marks T as contravariant — T only appears in input positions (parameters): interface Setter<in T> { set(value: T): void; }. in out T marks as invariant — T appears in both positions. Benefits: (1) TypeScript can skip expensive variance inference for complex types, significantly improving compilation performance. (2) You explicitly document the intended variance, catching bugs when you accidentally use T in the wrong position. (3) Better error messages. TypeScript still infers variance automatically, but adding annotations enforces the intent and speeds up type-checking for deeply parameterized generic types in large codebases.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.