【问题标题】:Typescript Index Signature and methods in the implementing class doesn't work实现类中的打字稿索引签名和方法不起作用
【发布时间】: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 '() =&gt; T[]' is not assignable to string index type 'T'.

这甚至可能吗? 如果是,我怎样才能为我的班级创建方法?

【问题讨论】:

  • 为什么没有答案?如果您不能向实现类添加任何功能(nameley;方法),那么索引签名几乎毫无价值......
  • 我认为这是重复的(第一个答案):stackoverflow.com/questions/15877362/…

标签: typescript dictionary generics index-signature


【解决方案1】:

在进入 TypeScript 时遇到了非常相似的事情。只是向一个类添加一个函数就破坏了事情,没关系实际调用该函数。

“问题”似乎源于您实际上可以将类用作接口这一事实。在您的示例中,您可以毫无问题地执行以下操作。

let myobject: Dictionary<string>;
myobject = {'name': 'John'};

但请注意,虽然您将对象声明为 Dictionary 类型,但它实际上并不是 Dictionary 类的实例,而只是一个常规的 javascript 对象。

Dictionary 类添加任何方法都会导致原始错误。

我们的解决方案是注意何时拥有符合接口的对象以及何时拥有类的实例。我上面的例子真的应该是……

let myobject: IDictionary<string>;
myobject = {'name': 'John'};

如果我想说向Dictionary 类添加一个方法并使用它,我需要一个Dictionary 对象

let myobject: IDictionary<string>;
myobject = {'name': 'John'};

let myinstance: Dictionary<string>;
myinstance = new Dictionary(myobject);
myinstance.getValues();

回到你原来的问题,我猜你是在声明 Dictionary 类型的东西,而实际上它应该是 IDictionary 类型的东西?

另外,如果有人有关于使用类作为接口的信息/文档/参考,或者我在该主题上大错特错,请告诉我!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2018-12-15
    • 2021-03-06
    • 1970-01-01
    相关资源
    最近更新 更多