【发布时间】:2018-04-19 15:33:36
【问题描述】:
我正在尝试创建我自己的 Typescript 字典,例如类,但要在我的代码中使用一些自定义方法。
我可以像这样创建基本字典:
export interface IDictionary<T> {
[property: string]: T;
};
export class Dictionary<T> implements IDictionary<T> {
[property: string]: T;
constructor() {}
}
这很好用……但是…… 如果我尝试在此类中创建一个方法,例如
export class Dictionary<T> implements IDictionary<T> {
[property: string]: T;
constructor() {}
public getValues(): T[] { // this will give the error
return Object.values(this);
}
}
我收到此错误:
Property 'getValues' of type '() => T[]' is not assignable to string index type 'T'.
这甚至可能吗? 如果是,我怎样才能为我的班级创建方法?
【问题讨论】:
-
为什么没有答案?如果您不能向实现类添加任何功能(nameley;方法),那么索引签名几乎毫无价值......
-
我认为这是重复的(第一个答案):stackoverflow.com/questions/15877362/…
标签: typescript dictionary generics index-signature