Sub topic 8
Classes and private members
This chapter assumes you know the basics of TypeScript classes (fields, methods, extends, and the public, private and protected modifiers). It also assumes you have read the earlier chapters on assignability and object shapes. Classes follow the same shape-based rules as other object types, with one exception. Members declared private, protected or #private make a class compare by declaration, not by shape.
Instance types are compared by shape
A class declaration creates two things: a value (the constructor function) and a type (the shape of its instances). When you write Point in a type position, you get the instance shape. The class name carries no special weight.
class Point2D {
constructor(public x: number, public y: number) {}
}
class Coord {
x = 0;
y = 0;
label = "origin";
}
const p: Point2D = new Coord(); // OK: Coord has x: number and y: numberCoord never mentions Point2D, and it has an extra label member. Neither fact matters. A Coord has everything a Point2D requires, so it is assignable. The rule is the same as for interfaces: the source must contain every member of the target, with compatible types.
Methods work the same way. Two unrelated classes with a speak(): string method are interchangeable wherever that method is all that is required.
Private and protected members break the shape rule
Now add a private member:
class A {
private secret = 1;
}
class B {
private secret = 1;
}
const a: A = new B();
// Error: Types have separate declarations of a private property 'secret'.Both classes have the same member name, the same type and the same visibility. By shape alone they are identical, yet the assignment fails. When a member is private or protected, TypeScript requires the source and target to get that member from the same declaration. A copy with the same name does not count.
The same rule applies when only one side has the private member:
class Account {
private balance = 0;
deposit(n: number) {
this.balance += n;
}
}
const fake: Account = { deposit(n: number) {} };
// Error: Property 'balance' is missing in type '{ deposit(n: number): void; }'
// but required in type 'Account'.An object literal cannot supply a private member of someone else's class. The only values that can have Account's private balance are instances of Account and of its subclasses.
Subclasses share the declaration
A subclass inherits the private member from the same declaration, so it remains assignable to its base class:
class Base {
private id = 1;
}
class Derived extends Base {
extra = true;
}
const b: Base = new Derived(); // OK: 'id' originates in Baseprotected follows the same rule. A subclass may also redeclare a protected member as public, which widens access:
class Token {
protected value = "x";
}
class OpenToken extends Token {
public value = "y";
}
const t: Token = new OpenToken(); // OKA subclass cannot go the other way and narrow a public member to private. That fails with its own error at the class declaration.
The decision the checker makes
`#private` fields behave the same way
TypeScript also supports the JavaScript #name syntax. For assignability it works like private:
class A {
#secret = 1;
}
class B {
#secret = 1;
}
const a: A = new B();
// Error: Property '#secret' in type 'B' refers to a different member
// that cannot be accessed from within type 'A'.The two syntaxes differ at runtime, not in the type check:
| Feature | `private` keyword | `#name` field |
|---|---|---|
| Makes classes nominal in assignability | Yes | Yes |
| Enforced at runtime | No, erased when compiled | Yes, by the JavaScript engine |
| Reachable with `obj["name"]` | Yes, an intentional escape hatch | No |
| Visible in `keyof` | No | No |
The private keyword exists only at compile time. The compiler allows bracket access with a string literal, and nothing stops it at runtime:
class Vault {
private code = 1234;
}
const v = new Vault();
// console.log(v.code); // Error: Property 'code' is private
console.log(v["code"]); // 1234: allowed on purpose, and the value is public at runtimeUse #name when you need real privacy. Use private when you want compile-time guidance and simple debugging.
Interfaces that extend classes
An interface can extend a class. It inherits the class's members, including private ones, but not their implementations. The result is an interface that only the class and its subclasses can satisfy:
class Control {
private state = 0;
select() {
this.state++;
}
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() {}
}
class Picture implements SelectableControl {
select() {}
}
// Error: Class 'Picture' incorrectly implements interface 'SelectableControl'.
// Types have separate declarations of a private property 'state'.This is a way to say "any subclass of Control" in the type system. It is rarely needed, but it shows that the declaration-origin rule follows private members wherever they are inherited.
The constructor side is separate
The class name in a value position refers to the constructor function. Its type is typeof ClassName. It includes static members and the construct signature, and it is compared independently of the instance type.
class Counter {
static created = 0;
constructor(public n: number) {
Counter.created++;
}
}
type Factory = new (n: number) => { n: number };
const make: Factory = Counter; // OK: the construct signature matchesStatic members do not affect whether an instance is assignable to another instance type. Two points to remember:
- A class with a
privateorprotectedconstructor cannot be assigned to a type with a public construct signature. The checker rejects it because it would expose a constructor that the class tried to hide. - Static
privatemembers are tracked by declaration just like instance ones, but only for comparisons betweentypeoftypes.
Consequences in everyday code
The declaration-origin rule has practical effects.
- Test doubles stop working. If a function takes
AccountandAccounthas a private member, you cannot pass a plain object literal as a mock. You must subclass or cast. - Adding a private member is a breaking change. Before, any object with the right public shape was accepted. After, only real instances are. Callers who passed structural look-alikes now get errors.
- Different copies of a package can conflict. If two versions of a library both declare
class Client { private token: string }, instances from one version are not assignable to the other's type. The class is declared twice, so the declarations differ.
The usual remedy is to depend on an interface that lists only what the function needs:
class Account {
private balance = 0;
deposit(n: number) {
this.balance += n;
}
}
interface Depositor {
deposit(n: number): void;
}
function pay(target: Depositor, amount: number) {
target.deposit(amount);
}
pay(new Account(), 10); // OK
pay({ deposit(n: number) {} }, 10); // OK: a mock works againIf you need the public surface of an existing class without writing the interface, keyof helps. It lists only public members, so Pick<Account, keyof Account> produces the public shape:
type PublicAccount = Pick<Account, keyof Account>;
const stub: PublicAccount = { deposit(n: number) {} }; // OKSummary of the rules
- Public members are compared by name and type, as with any object type.
private,protectedand#namemembers must come from the same declaration in source and target.- Subclasses pass because they inherit the declaration. Unrelated classes with look-alike private members fail.
- Instance types and
typeof Classconstructor types are compared separately. - Object literals can never satisfy a class type that has non-public members.
Exercise
Given the code below, which of the two assignments compile, and why? class Engine { private rpm = 0; start() {} } class TurboEngine extends Engine { boost() {} } class FakeEngine { private rpm = 0; start() {} } const e1: Engine = new TurboEngine(); const e2: Engine = new FakeEngine();
Show answer
Only e1 compiles. TurboEngine extends Engine, so its rpm member comes from the same declaration, and the extra boost method does not matter. FakeEngine has a private rpm with the same name and type, but it is declared separately, so the checker reports that the types have separate declarations of a private property.
Exercise
A function report(a: Account) is hard to test because Account has a private balance field and tests pass object literals. Give two ways to make the function accept a mock without removing balance.
Show answer
First, change the parameter to an interface that lists only the public members the function uses, such as interface Depositor { deposit(n: number): void }. Second, use Pick<Account, keyof Account>, because keyof Account contains only public members, so the resulting type has no private members and an object literal can satisfy it.