Sub topic 20
How private and protected members affect type compatibility
This chapter assumes you know TypeScript's structural typing, the public, private and protected modifiers, and extends and implements. It explains one rule: a private or protected member changes how TypeScript decides whether one class type can be used where another is expected.
The default: structural typing
TypeScript compares types by shape. A value fits a type if it has every required member with a compatible type. Names of declarations do not matter.
class Point2D {
constructor(public x: number, public y: number) {}
}
const p: Point2D = { x: 1, y: 2 }; // OK: the shape matchesA plain object literal is accepted here because Point2D has only public members.
The rule: private and protected members come from one declaration
When a class has a private or protected member, shape alone is no longer enough. The other type must contain that same member, and the member must originate in the same declaration. In practice this makes such classes behave almost like nominal types, where the declaration's identity matters.
class A {
private x = 1;
getX(): number {
return this.x;
}
}
class B {
private x = 1;
getX(): number {
return this.x;
}
}
// @ts-expect-error: Types have separate declarations of a private property 'x'.
const a: A = new B();A and B have identical shapes, but each x is declared separately. TypeScript treats them as unrelated members, so the assignment fails.
The same rule applies to protected members. Two unrelated classes that each declare protected id are not interchangeable.
What is still compatible
A subclass inherits the member from the base declaration, so a subclass instance is assignable to the base type. The reverse fails because the base lacks the subclass's additions.
class Base {
protected id = 1;
describe(): string {
return `id=${this.id}`;
}
}
class Derived extends Base {
extra = "e";
}
const b: Base = new Derived(); // OK: id comes from Base's declaration
// @ts-expect-error: Property 'extra' is missing in type 'Base'.
const d: Derived = new Base();Object literals and test doubles
Because of this rule, a hand-written object can never satisfy a class type that has a private member. This matters when you write tests with fakes.
class Mailer {
private queue: string[] = [];
send(to: string): void {
this.queue.push(to);
}
}
function notify(m: Mailer): void {
m.send("[email protected]");
}
const fake = { send(_to: string): void {} };
// @ts-expect-error: Property 'queue' is missing in type '{ send(_to: string): void; }'.
notify(fake);The fake has the right public method, but it cannot supply queue. The usual fix is to depend on an interface that describes only the public behavior.
interface Sender {
send(to: string): void;
}
function notifySender(s: Sender): void {
s.send("[email protected]");
}
class RealMailer implements Sender {
private queue: string[] = [];
send(to: string): void {
this.queue.push(to);
}
}
const fakeSender = { send(_to: string): void {} };
notifySender(fakeSender); // OK
notifySender(new RealMailer()); // OKNow both the real class and the fake fit, because Sender has no private members.
Interfaces that extend classes
An interface can extend a class. It inherits the class's members, including private and protected ones. Only that class or its subclasses can then implement the interface.
class Control {
private state = 0;
select(): void {
this.state++;
}
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {} // OK
// @ts-expect-error: 'state' is private in Control, so Picture cannot implement the interface.
class Picture implements SelectableControl {
select(): void {}
}This is a deliberate way to say "only members of this class family are allowed here."
ECMAScript `#private` fields follow the same idea
A #private field is also tied to its declaring class. Two classes with identical shapes and separate #x fields are not assignable to each other. The difference from the private keyword is that the restriction also exists at runtime, as covered in the previous chapter.
class C {
#x = 1;
getX(): number {
return this.#x;
}
}
class D {
#x = 1;
getX(): number {
return this.#x;
}
}
// @ts-expect-error: '#x' in D refers to a different member than '#x' in C.
const c: C = new D();Gotchas and decision criteria
- Same name and type is not enough. Copying a class definition into another file creates a different declaration, and the two types will not mix.
- Duplicate package versions can break compatibility. If two versions of a library each ship a class with private members, values from one version are rejected where the other version's type is expected.
- Visibility mismatches fail. A class with
public xand a class withprivate xare incompatible, and the error mentions that the property is private in one type but not the other. - Private members make mocking harder. If callers need substitutes, accept an interface. If you want to restrict values to one class family, accept the class.
- Exported classes leak this rule. A public function that takes a class with private members forces callers to pass real instances. Document that, or accept an interface instead.
Exercise
A function save(repo: UserRepo) is called in a test with { add(u: string) {} }. UserRepo has a public add(u: string): void method and a private db: Database field. The call fails to compile. Give two ways to fix it and say what each one changes.
Show answer
Option 1: define interface Repo { add(u: string): void }, change the parameter to repo: Repo, and let UserRepo implements Repo. The fake now fits because the interface has no private members. Option 2: keep the parameter type and pass a real UserRepo, or a subclass of it that overrides add. This keeps the restriction to the UserRepo family but requires constructing a real or derived instance. Option 1 is usually better for testing because it removes the dependency on private db.