0

IMHO, this is not a duplicate of this question. Here is a minimal example:

class Indexer {
  private readonly someIndex = 200;
  public getIndex() { return this.someIndex; }
}

class Person extends Indexer {}
class Something<T extends Indexer> {
  s = new Map<number, T>();
  insert(t: T){ /* ... */ }
}

const c1 = new Something<         Person >();
const c2 = new Something<Readonly<Person>>();
  • On one hand my class needs to subclass Indexer
  • On the other hand it needs to be Readonly

I can not achieve the two properties together:

$ npx tsc --target es2020 main.ts
main.ts:13:26 - error TS2344: Type 'Readonly<Person>' does not satisfy the constraint 'Indexer'.
  Property 'someIndex' is missing in type 'Readonly<Person>' but required in type 'Indexer'.

13 const c2 = new Something<Readonly<Person>>();
                            ~~~~~~~~~~~~~~~~

  main.ts:2:20
    2   private readonly someIndex = 200;
                         ~~~~~~~~~
    'someIndex' is declared here.
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87

1 Answers1

1

That doesn't work because Readonly is a mapped type and mapped types are dropping the private keys.

Thus the error you get :

Type 'Readonly<Person>' does not satisfy the constraint 'Indexer'.
  Property 'someIndex' is missing in type 'Readonly<Person>' but required in type 'Indexer'.

Playground

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134