是否有可能通过通用函数获得有关对象键的智能帮助

时间:2018-12-14 08:33:58

标签: typescript

这是一个基本示例。可以在智能感知中获取密钥吗?

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`

嗯...我应该再添加一些文字

1 个答案:

答案 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