Sub topic 11
Generic Types and Unused Type Parameters
This chapter assumes you know basic TypeScript syntax, including interfaces, type aliases and generics declarations such as Box<T>. It also assumes you have read the earlier chapters on assignability and object shapes. Here you will see how the checker compares two instantiations of the same generic type, why an unused type parameter makes them interchangeable, and how to avoid the bugs this causes.
The rule: compare the members, not the arguments
In a nominal language, List<string> and List<number> are different types because their names and arguments differ. TypeScript does not compare names or arguments first. It asks whether the two types have compatible members.
For a generic type, the checker works in two steps:
- Substitute the type arguments into the declaration.
Box<number>becomes{ value: number }. - Compare the resulting shapes with the usual assignability rules.
This means the type parameter only matters through the places where it is used. If it appears in no member, it has no effect on the comparison.
An unused type parameter changes nothing
Look at this example.
interface Tag<T> {}
const a: Tag<string> = {};
const b: Tag<number> = a; // OK: T is never used, so the shapes are identical
interface Box<T> {
value: T;
}
const nb: Box<number> = { value: 1 };
const wide: Box<number | string> = nb; // OK: compared by the type of 'value'Tag<string> and Tag<number> both expand to {}. Nothing distinguishes them, so each is assignable to the other. The declaration looks as if it records the type argument, but the checker has nothing to compare.
Box<number> to Box<number | string> works for a different reason. The value member is number in the source and number | string in the target. A number fits in number | string, so the assignment is allowed.
The checker does not need to expand every generic comparison. For performance it often computes how each type parameter is used (covariant, contravariant, invariant or unused) and compares type arguments directly. These variance results must agree with the structural answer, so you can reason with the structural model.
Where the type parameter appears decides the direction
The position of T in a member decides which direction of assignment is allowed. This is variance. It follows from the function rules in the chapters on function compatibility and strictFunctionTypes.
| Position of `T` | Example member | `Box<Dog>` to `Box<Animal>` | `Box<Animal>` to `Box<Dog>` |
|---|---|---|---|
| Output only | `get(): T` | Allowed | Error |
| Input only (strict) | `set: (v: T) => void` | Error | Allowed |
| Both | `value: T` with a setter function | Error under strict function types | Error |
| Not used | none | Allowed | Allowed |
The "Both" row needs care. A plain property such as value: T is treated as covariant. The checker does not enforce write safety for properties, which is a known unsoundness. Only function-typed members declared as properties, using strict function types, are checked contravariantly.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface Producer<T> {
get(): T;
}
interface Consumer<T> {
set: (v: T) => void;
}
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer; // OK: output position
declare const animalConsumer: Consumer<Animal>;
const dogConsumer: Consumer<Dog> = animalConsumer; // OK: input position, wider accepts narrower
declare const dogConsumer2: Consumer<Dog>;
const animalConsumer2: Consumer<Animal> = dogConsumer2;
// Error under strictFunctionTypes: Animal is not assignable to DogUnder "strict": true, Consumer<Dog> to Consumer<Animal> fails because a consumer that expects a Dog cannot safely receive any Animal.
Method syntax is looser
If you write the member as a method (set(v: T): void) instead of a function-typed property, parameters are compared bivariantly even under strictFunctionTypes. Then both directions are accepted. This exception exists so that common types such as Array<T> stay convenient.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface MethodConsumer<T> {
set(v: T): void;
}
interface PropertyConsumer<T> {
set: (v: T) => void;
}
declare const mDog: MethodConsumer<Dog>;
const mAnimal: MethodConsumer<Animal> = mDog; // OK: method parameters are bivariant
declare const pDog: PropertyConsumer<Dog>;
const pAnimal: PropertyConsumer<Animal> = pDog;
// Error under strictFunctionTypesThe common error: a phantom type parameter that does nothing
Developers often add a type parameter to record intent, such as the kind of ID or the unit of a number, and expect the compiler to enforce it. If the parameter is unused, it enforces nothing.
interface Id<T> {
value: string;
}
interface User {
name: string;
}
interface Order {
total: number;
}
declare function loadUser(id: Id<User>): void;
const orderId: Id<Order> = { value: "o1" };
loadUser(orderId); // OK, probably not what you intendedBoth Id<User> and Id<Order> expand to { value: string }. The call compiles, and a bug reaches runtime.
There are two honest fixes.
Fix 1: use the parameter in a member
Give T a place in the shape. A property typed with T creates a real difference, even if it holds nothing at runtime.
interface Id<T> {
value: string;
readonly __entity?: T;
}
interface User {
name: string;
}
interface Order {
total: number;
}
declare function loadUser(id: Id<User>): void;
const orderId: Id<Order> = { value: "o1" };
loadUser(orderId);
// Error: Type 'Id<Order>' is not assignable to type 'Id<User>'.The optional property __entity?: T is never set. It exists only so the shapes differ. Because the property is read-only and covariant, Id<Order> is checked against Id<User> by comparing Order | undefined to User | undefined, which fails because Order lacks name.
This works only when the type arguments themselves are structurally different. If User and Order had the same members, the ids would again be interchangeable. That is the same limit that applies to every structural type.
Fix 2: use a brand
When the arguments might be structurally identical, or when you need to distinguish plain strings, use a brand as covered in the branding chapter.
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
declare function getUser(id: UserId): void;
const oid = "o1" as OrderId;
getUser(oid); // Error: OrderId is not assignable to UserIdHere the string literal "UserId" is a type argument that appears in a member, so it matters to the comparison.
Generics and inference interact with this rule
Inference uses the same structural view. When you call a generic function, TypeScript infers T from where the parameter type mentions T. If the parameter type does not mention T in a member that the argument provides, there is nothing to infer from, and T falls back to its constraint or to unknown.
interface Tag<T> {}
function describe<T>(x: Tag<T>): T {
return undefined as unknown as T;
}
const s: Tag<string> = {};
const result = describe(s); // result is unknown, not stringBecause Tag<string> has no members that mention T, inference cannot recover string from it. In current versions, TypeScript can sometimes keep a reference to the alias or interface and infer from type arguments directly, so you may see string in some cases. Do not rely on this. If you need inference to work, use T in a member.
A worked example: a typed event emitter
Here is a small example in which the type parameter is used in a function-typed property. The parameter is therefore checked, and mixing up emitters is an error.
interface Emitter<E> {
emit: (event: E) => void;
}
interface Click {
x: number;
y: number;
}
interface Key {
code: string;
}
declare const clickEmitter: Emitter<Click>;
declare const keyEmitter: Emitter<Key>;
const a: Emitter<Click> = clickEmitter; // OK
const b: Emitter<Key> = clickEmitter;
// Error: Type 'Click' is not assignable to type 'Key'
// (the parameter of 'emit' is checked contravariantly)Check the reasoning step by step. emit is a function-typed property, so its parameter is compared contravariantly. To assign Emitter<Click> to Emitter<Key>, a Key would have to be assignable to Click. A Key has no x or y, so the assignment fails.
Checking your understanding of the rules
- If a type parameter is unused, any two instantiations are interchangeable.
- If it appears only in output positions, instantiations are assignable in the narrower-to-wider direction.
- If it appears only in input positions of function-typed properties under
strictFunctionTypes, the direction reverses. - Method syntax relaxes the input case to bivariance.
- Plain mutable properties are treated as covariant, even though that is unsound for writes.
The last point matters in practice.
interface Box<T> {
value: T;
}
const strings: Box<string> = { value: "a" };
const wide: Box<string | number> = strings; // OK, but unsound
wide.value = 42; // Allowed by the checker
console.log(strings.value.toUpperCase());
// Compiles, but throws at runtime: strings.value is now the number 42The checker allows the assignment because it compares value covariantly. Both variables refer to the same object, so writing a number through wide corrupts strings. If you need protection from this, use readonly properties on types you hand out, or keep writes behind a function-typed property so that strict function types applies.
Summary of the decision
When you add a type parameter, ask what member will use it.
- If it is used in a member, the checker enforces it according to its position.
- If it is not used, remove it, or add a brand or a phantom member on purpose.
- If you rely on it to separate two ids or units, check that the type arguments differ structurally, or use a brand.
Exercise
Given the declarations below, which of the three assignments compile under "strict": true, and why? interface Animal { name: string } interface Dog extends Animal { bark(): void } interface Phantom<T> { id: string } interface Source<T> { get(): T } interface Sink<T> { put: (v: T) => void } declare const p: Phantom<Dog>; declare const s: Source<Dog>; declare const k: Sink<Animal>; const one: Phantom<number> = p; const two: Source<Animal> = s; const three: Sink<Dog> = k;
Show answer
All three compile. The first compiles because T is unused in Phantom, so Phantom<Dog> and Phantom<number> both expand to { id: string }. The second compiles because T appears only in the return position of get, which is covariant, and Dog is assignable to Animal. The third compiles because T appears only as the parameter of a function-typed property, which is contravariant under strictFunctionTypes, and Sink<Animal> accepts any Animal, so it can stand in for a Sink<Dog>.
Exercise
The type Meters<T> below is meant to stop you passing a Feet value where Meters is expected. Why does it fail, and how would you fix it? interface Unit<U> { amount: number } type Meters = Unit<"m">; type Feet = Unit<"ft">; declare function walk(distance: Meters): void; const f: Feet = { amount: 10 }; walk(f);
Show answer
U is never used in a member, so Unit<"m"> and Unit<"ft"> both expand to { amount: number } and are interchangeable. The call compiles. Fix it by using U in a member, for example adding readonly _unit?: U to Unit, so that "m" and "ft" produce different shapes. Alternatively, use a brand such as number & { readonly _brand: "m" }.