1

Given class MyClass, why are private constructor fields required when implementing an object with the type MyClass?

They're private, so shouldn't they be ignored when implementing an object that conforms to the class?

Tiny Example

class MyClass {
  constructor(
    private privateString: string,
  ) {}

  method1(): number {
    return 1;
  }
  method2(): number {
    return 2;
  }
}

/*
Property 'privateString' is missing in type '{ method1: () => number; method2: () => number; }' 
but required in type 'MyClass'.ts(2741)
*/
const Stub: MyClass = {
  method1: () => 1,
  method2: () => 2,
};

/*
Type '{ privateString: string; method1: () => number; method2: () => number; }' 
  is not assignable to type 'MyClass'.
Property 'privateString' is private in type 'MyClass' 
  but not in type '{ privateString: string; method1: () => number; method2: () => number; }'.ts(2322)
*/
const Stub: MyClass = {
  privateString: '',
  method1: () => 1,
  method2: () => 2,
};

Tested on Typescript 4.4.3

Ken White
  • 123,280
  • 14
  • 225
  • 444
Ben Winding
  • 10,208
  • 4
  • 80
  • 67
  • 1
    [This behavior is intentional](https://www.typescriptlang.org/docs/handbook/type-compatibility.html#private-and-protected-members-in-classes). Are you looking for speculation on why they designed it that way? – Nicholas Tower Sep 23 '21 at 00:51
  • That's so strange, I guess _private_ members, are not truely private to that class then, if anything implementing the class requires them. Yes I was wondering how to avoid this issue when mocking a class with a POJO – Ben Winding Sep 23 '21 at 01:07
  • Class private members are visible to other instances of the same class, as [the answer](https://stackoverflow.com/a/48953930/2887218) to the linked question demonstrates, and as you can see in [this example](https://tsplay.dev/WYYbdW). – jcalz Sep 23 '21 at 02:00

0 Answers0