Sub topic 16
Classes and private members
This chapter assumes you know the basic rules of structural assignability from the earlier chapters, including how interfaces and object types are compared. It also assumes you can write TypeScript classes with public, private, and protected modifiers. Here you will see where classes follow those structural rules and where private and protected members change them.
Classes are structural by default
A class declares two things: a value (the constructor) and a type (the shape of its instances). The instance type is compared the same way as an interface. Only members matter, and the class name does not.
class Point2D {
constructor(public x: number, public y: number) {}
}
class Vec {
x = 0;
y = 0;
length(): number {
return Math.hypot(this.x, this.y);
}
}
interface HasXY {
x: number;
y: number;
}
const p: Point2D = new Vec(); // OK: Vec has x and y, and extra members are allowed
const h: HasXY = new Point2D(1, 2); // OK: a class instance satisfies an interface by shapeVec never mentions Point2D, and no implements clause is needed. If every required public member is present with a compatible type, the assignment compiles.
Private and protected members change the rule
A private or protected member is not matched by name and type alone. The compiler also requires that the member in the source comes from the same declaration as the member in the target.
class A {
private id = 1;
}
class B {
private id = 1;
}
class C extends A {}
const fromB: A = new B(); // Error: separate declarations of private property 'id'
const fromC: A = new C(); // OK: C inherits id from the declaration in A
const literal: A = { id: 1 }; // Error: property 'id' is private in type 'A'B has an id of the same type, but it is a different declaration. C inherits the id declared in A, so the declarations match. The object literal also fails, because a plain object cannot have a private member that originates in A.
Protected members follow the same idea, with one addition. The source member may originate in the target's declaration or in any class derived from it.
class Base {
protected value = 0;
}
class Derived extends Base {
show(): number {
return this.value;
}
}
class Other {
protected value = 0;
}
const d: Base = new Derived(); // OK
const o: Base = new Other(); // Error: 'value' originates in a different declarationThe direction matters
The extra rule applies only when the target type has the private or protected member. A class with private members can still be assigned to a type that does not mention them.
class Account {
private balance = 0;
constructor(public owner: string) {}
}
interface Owned {
owner: string;
}
const ok: Owned = new Account("Ada"); // OK: Owned does not require balance
const bad: { owner: string; balance: number } = new Account("Ada"); // Error: 'balance' is private in 'Account'The second assignment fails for a different reason. The target declares balance as a public property, but in the source it is private. TypeScript reports that the property is private in one type but not in the other. This makes private members useful for reducing what an interface-typed consumer can see.
How the compiler decides
The static side and constructor types
A class name used as a value has its own type, typeof ClassName. It is a constructor type, and it is compared separately from instance types. A constructor type is written new (args) => Instance.
abstract class Shape {
abstract area(): number;
}
class Square extends Shape {
constructor(private side: number) {
super();
}
area(): number {
return this.side ** 2;
}
}
function build(ctor: new (side: number) => Shape): Shape {
return new ctor(2);
}
build(Square); // OK: the constructor takes a number and returns a Square, which is a Shape
build(Shape); // Error: cannot assign an abstract constructor type to a non-abstract oneTwo edge cases come up often:
- Abstract classes. An abstract constructor cannot be passed where a concrete
newsignature is expected. If you need to accept abstract classes, writeabstract new (...args: any[]) => Shape. - Private and protected constructors. A class with a private constructor cannot be assigned to a
new (...) => Ttype, because the constructor is not publicly callable.
Gotchas
- Empty classes accept almost anything. A class with no members has an empty instance type, so
const e: Empty = {}compiles. Primitives such as42are also accepted. Add a private member if you want to prevent that. - Privacy is compile-time only. The
privatekeyword is erased at runtime, so(a as any).idstill works. Only#privatefields are enforced at runtime. - Subclass overrides must stay compatible. A derived class is checked for assignability to its base. Making a protected member public in a subclass is allowed, but changing a member to an incompatible type is an error.
- Branding is another route. A private member makes a class nominal-like. For plain strings or numbers you cannot add a private member, so a later chapter covers branded types.
Exercise
Given class Meters { private unit = "m"; constructor(public value: number) {} } and class Feet { private unit = "m"; constructor(public value: number) {} }, does const m: Meters = new Feet(3); compile? What if Feet is declared as class Feet extends Meters {}?
Show answer
The first version does not compile. Both classes have the same shape, but each declares its own private unit, so TypeScript reports separate declarations of the private property. With class Feet extends Meters {}, the private unit is inherited from the declaration in Meters, so the assignment compiles.
Exercise
Why does const x: { owner: string; balance: number } = new Account("Ada"); fail for the Account class above, while const y: { owner: string } = new Account("Ada"); succeeds?
Show answer
The target in the first line requires a public balance property, but in Account it is private, and TypeScript rejects that mismatch. The target in the second line asks only for owner, which is public in Account, so the structural check passes. Private members matter only when the target has them or declares a conflicting public member of the same name.