这是一个基本示例。可以在智能感知中获取密钥吗?
export class Test<K extends string, V> {
private data: {[P in K]: V} = {} as any;
addValue (key: K, value: V): this {
this.data[key] = value;
return this;
}
build (): {[P in K]: V} {
return this.data;
}
}
const test = new Test()
.addValue('A', 123)
.addValue('B', '111')
.build();
test. <-- I want `test` to know about keys in `this.data`
嗯...我应该再添加一些文字
答案 0 :(得分:2)
您可以执行此操作,但是在每个步骤(即每个addValue
调用)中,您都需要更改对象的类型以添加新的键和值。
export class Test<T> {
private data: T = {} as any;
addValue<KAdd extends string, VAdd>(key: KAdd, value: VAdd){
let newThis = this as unknown as Test<Record<KAdd, VAdd>>
newThis.data[key] = value;
return newThis as Test<T & Record<KAdd, VAdd>>;
}
build (): T {
return this.data;
}
}
const test = new Test()
.addValue('A', 123)
.addValue('B', '111')
.build();
test.A // number
test.B // string