Sub topic 3
Classes, Variance, and Nominal-Style Safety
Assume you know TypeScript interfaces, type aliases, functions, and JavaScript classes. This chapter focuses on cases where structural typing needs extra rules.
Classes and private members
TypeScript usually compares classes by their public members. A class with the required methods and properties can match another type. However, private and protected members must come from the same class declaration. They make classes behave partly like nominal types, where the declared origin matters.
class Account {
private balance = 0;
}
class OtherAccount {
private balance = 0;
}
const account: Account = new OtherAccount();
// Error: separate declarations of private property 'balance'Weak type detection
A weak type has only optional properties. TypeScript reports an error when a value has no property in common with that type. This often catches misspelled option names.
interface Options {
color?: string;
width?: number;
}
const settings = { colour: "red" };
const options: Options = settings;
// Error: no properties in common with 'Options'Parameter variance and `strictFunctionTypes`
With strictFunctionTypes, a function may accept a broader parameter type where a narrower type is expected. The reverse is unsafe. A function returning a value must return a compatible, usually narrower, type.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
let handleDog: (dog: Dog) => void;
handleDog = (animal: Animal) => {}; // OK
let handleAnimal: (animal: Animal) => void;
handleAnimal = (dog: Dog) => {};
// Error: an Animal might not have bark()A function that ignores extra arguments can also fit a function type that supplies those arguments.
Generic types and unused type parameters
Generic compatibility depends on the members produced by the type parameter. If the parameter appears nowhere, it has no effect on the shape.
interface Tag<T> {}
const textTag: Tag<string> = {};
const numberTag: Tag<number> = textTag; // OKBranded types for nominal-style safety
A brand adds a compile-time-only property. It prevents different values with the same runtime type from being mixed.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
const userId = "u1" as UserId;
const orderId = "o1" as OrderId;
function loadUser(id: UserId) {}
loadUser(userId); // OK
loadUser(orderId); // ErrorPitfall: `Object.keys`
A value typed as Point may contain extra properties at runtime. Therefore, Object.keys returns string[], not (keyof Point)[]. The type system cannot safely assume that runtime keys contain only declared keys.
Exercise
Why are two classes with identical private property names incompatible?
Show answer
Their private properties come from different declarations, so the classes do not have the same nominal identity.