【问题标题】:Generic Types in Typescript Cannot be used to index objectTypescript 中的泛型类型不能用于索引对象
【发布时间】:2021-02-22 20:09:59
【问题描述】:

我正在尝试创建以使用泛型键入我的类,但它会抛出一个错误

class CustomDataStructure<T> {
    public _data: object;

     constructor() {
        this._data = {};
        }
    public getAndDeleteRandomKey(): void {
        const allExistingKeys = Object.keys(this._data);
        const randomKey = allExistingKeys[Math.floor(Math.random()*(allExistingKeys.length))];
        this.removeItem(randomKey);
    }
   
    public addItem(value: T): void {
        console.log("adding");
        console.log(this._data)
        this._data[value] = new Date().getTime();
    }

    public removeItem(key: T): void {
        delete this._data[key];
    }
}

let ss = new CustomDataStructure<string>();
ss.addItem("hello");
ss.addItem("hello2");

这会引发 2 个不同的错误

  1. “T”类型的参数。“T”可以用与“字符串”无关的任意类型实例化。

  2. 类型“T”不能用于索引类型“对象”

我这里有什么遗漏吗

TypeScriptPlayground

【问题讨论】:

  • 为什么在这里使用泛型类型?您会使用哪些其他可能的类型来键入数据对象?
  • 键也可以是数字
  • 他们可以,但最终在幕后他们被强制转换为字符串。

标签: typescript generics casting


【解决方案1】:

这样做的原因是泛型 T 也可能是一个复杂对象,例如一个类实例,你只能使用原始对象作为键

const object = {}
object["myKey"] = true // works 
object[new Date()] = true // not works, because is a complex object 

考虑使用地图,请参阅

Playground

class CustomDataStructure<T> {
    private _data: Map<T, any> = new Map();

     constructor() {}
    public getAndDeleteRandomKey(): void {
        const allExistingKeys = Array.from(this._data.keys());
        const randomKey = allExistingKeys[Math.floor(Math.random()*(allExistingKeys.length))];
        this._data.delete(randomKey);
    }
   
    public addItem(value: T): void {
        this._data.set(value, new Date().getTime())
    }


}

let ss = new CustomDataStructure<string>();
ss.addItem("hello");
ss.addItem("hello2");

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 2018-04-01
    • 2021-12-30
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多