下面是一个基本的例子。是否可以在智能感知中获取密钥?
Code example
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
关于typescript - 是否有可能通过通用函数获得有关对象键的智能帮助,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53776023/