这是一个基本示例。是否有可能在智能感知中获取密钥?
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`
好吧...我应该再添加一些文字
您可以执行此操作,但是在每个步骤(即每个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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句