Sub topic 14
Comparing generic types
This chapter assumes you know generic interfaces and type aliases, the strictFunctionTypes rule for function parameters, and the idea of variance from the earlier chapters. It covers how the compiler decides whether Box<string> can be used where Box<string | number> is expected, and how generic functions are compared.
Same generic, different type arguments
When source and target are instantiations of the same generic interface, class, or alias, the compiler first compares the type arguments. It does not expand both types structurally. It uses the variance of each type parameter, which it works out from how the parameter is used in the declaration. The parameter is covariant if it appears only in output positions. It is contravariant if it appears only in input positions. It is invariant if it appears in both.
interface Box<T> {
readonly value: T;
}
interface Handler<T> {
handle: (input: T) => void;
}
declare let boxString: Box<string>;
declare let boxWide: Box<string | number>;
boxWide = boxString; // OK: T is only read, so Box is covariant
boxString = boxWide; // Error: string | number is not assignable to string
declare let handleString: Handler<string>;
declare let handleWide: Handler<string | number>;
handleString = handleWide; // OK: T is only consumed, so Handler is contravariant
handleWide = handleString; // Error: a string-only handler cannot accept numbersHandler<T> is contravariant only because handle is declared as a function-typed property and strictFunctionTypes is on. With method syntax, handle(input: T): void, the parameter is checked bivariantly, and both assignments above would compile.
If the same parameter is read and written through function-typed properties, it is invariant, and neither direction works unless the type arguments are identical:
interface Cell<T> {
get: () => T;
set: (value: T) => void;
}
declare let cellString: Cell<string>;
declare let cellWide: Cell<string | number>;
cellWide = cellString; // Error: set would accept numbers
cellString = cellWide; // Error: get could return numbersCommon variances
| Type | Variance of `T` | Reason |
|---|---|---|
| `ReadonlyArray<T>` | Covariant | `T` appears only in read positions. |
| `Array<T>` | Covariant (unsound) | The compiler allows it even though `push` writes `T`. |
| `Promise<T>` | Covariant | `T` is produced by `then` callbacks. |
| `(x: T) => void` | Contravariant | `T` is a parameter. |
| `Set<T>` | Covariant in practice | Method parameters are bivariant. |
| `Cell<T>` above | Invariant | `T` is both read and written through function-typed properties. |
Unused type parameters
Variance is derived from structure, so a parameter that the structure never uses has no effect on compatibility.
interface Tagged<T> {
id: number;
}
declare let tagString: Tagged<string>;
const tagNumber: Tagged<number> = tagString; // OK: T is never usedThis surprises people who use a phantom type parameter to tell types apart. The two types are identical once expanded, so Tagged<string> and Tagged<number> are interchangeable. If you want them to differ, T has to appear in a property or signature, or you can use a brand (covered in a later chapter).
When the type arguments are not compared directly
The variance shortcut applies only when both types come from the same declaration. For different declarations, such as Array<T> and ReadonlyArray<T>, or your own interface and a class, the compiler compares members structurally. It substitutes the type arguments into each member and checks the members one by one.
interface Named<T> {
readonly name: T;
}
class Person<T> {
constructor(public name: T) {}
}
declare let person: Person<string>;
const named: Named<string> = person; // OK: structural check of `name`
const namedWide: Named<string | number> = person; // OK: string is assignable to string | numberThe compiler may also fall back to a structural comparison when the variance computation is inconclusive. Recursive generic types are the usual example. The result is normally the same, but the error message can be longer, and checking is slower on large types.
Comparing generic functions
A generic function type has its own type parameters, and they are handled differently depending on whether the function is the source or the target.
When the source is generic and the target is not, the compiler infers the source's type parameters from the target's signature. A generic function therefore fits any specific signature it can be instantiated to:
const identity = <T>(value: T): T => value;
const numberId: (value: number) => number = identity; // OK: T is inferred as number
const stringId: (value: string) => string = identity; // OK: T is inferred as stringWhen the target is generic, its type parameters are treated as opaque types. The source has to work for every possible T, not just one:
const toNumber = (value: number): number => value;
const generic: <T>(value: T) => T = toNumber; // Error: T is not assignable to numberThe same opacity applies inside a generic function body. An unconstrained T is treated as unknown, and a constrained T is treated as its constraint:
function unconstrained<T>(value: T): string {
return value; // Error: T is not assignable to string
}
function constrained<T extends string>(value: T): string {
return value; // OK: T's constraint is string
}Constraints and defaults
A type argument must be assignable to its parameter's constraint, so the constraint check is itself an assignability check:
interface Repository<T extends { id: number }> {
find(id: number): T | undefined;
}
type UserRepo = Repository<{ id: number; name: string }>; // OK: extra property is fine
type BadRepo = Repository<{ name: string }>; // Error: property 'id' is missingTwo common mistakes follow from this chapter. The first is expecting Handler<Dog> to be assignable to Handler<Animal>, when the direction is reversed because the parameter is contravariant. The second is expecting a phantom parameter to separate two types. Check how T is actually used before reasoning about which direction should compile.
Exercise
Given interface Sink<T> { write: (value: T) => void }, interface Animal { name: string } and interface Dog extends Animal { bark(): void }, which assignment compiles under strict: Sink<Animal> to Sink<Dog>, or Sink<Dog> to Sink<Animal>? What would change if write used method syntax?
Show answer
Sink<Animal> to Sink<Dog> compiles. write is a function-typed property, so T is contravariant, and a sink that accepts any Animal can safely receive Dogs. Sink<Dog> to Sink<Animal> fails, because it could be given a non-Dog animal. With method syntax, write(value: T): void, the parameter is checked bivariantly, so both assignments would compile.
Exercise
Why does const b: Tagged<number> = tagString compile when interface Tagged<T> { id: number } and tagString is a Tagged<string>?
Show answer
T is never used in the structure, so Tagged<string> and Tagged<number> have the same members. The compiler finds no difference between them, and either type can be assigned to the other.