恕我直言,这不是这个问题的重复。这是一个最小的例子:
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>>();
- 一方面我的类需要子类化
Indexer
- 另一方面,它需要
Readonly
我无法同时实现这两个属性:
$ 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.
这不起作用,因为
Readonly
它是映射类型,并且映射类型正在删除私钥。因此你得到的错误是:
操场