【发布时间】: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 个不同的错误
-
“T”类型的参数。“T”可以用与“字符串”无关的任意类型实例化。
-
类型“T”不能用于索引类型“对象”
我这里有什么遗漏吗
【问题讨论】:
-
为什么在这里使用泛型类型?您会使用哪些其他可能的类型来键入数据对象?
-
键也可以是数字
-
他们可以,但最终在幕后他们被强制转换为字符串。
标签: typescript generics casting