【问题标题】:extend interfaces to be a dictionary将接口扩展为字典
【发布时间】:2016-01-22 13:45:26
【问题描述】:

我有一个角度资源接口,我想扩展它以从后端获取对象结构。它适用于除字典以外的任何接口类型:

export interface MyInterface extends angular.resource.IResource<any> {
  [key: string]: MyAnotherInterface;
}

Typescript 编译器给出一个错误,即无法找到来自 angular.resource.IResource 的所有属性,因为据我了解,另一个声明 [key: string]: MyAnotherInterface; 会覆盖可扩展单元的所有属性。所以,据我了解,问题在于字典声明非常严格,不允许在同一接口上使用其他属性。

我无法更改服务器返回的结构(仅仅因为 TS 而更改它是愚蠢的);同时我真的希望避免每次都写(&lt;any&gt;MyInterface).myProperty - 这真的很臭。

TypeScript 版本:1.7.5

如何解决这个问题?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    所以,据我了解,问题在于字典声明非常严格,不允许同一接口上的其他属性

    是的。你不能有一个可以被string 索引的字典,其中某些属性不符合general 结构(你的MyAnotherInterface)。

    我无法更改服务器返回的结构(仅仅因为 TS 而更改它是愚蠢的);

    你可以这样做:

    export interface MyInterface extends angular.resource.IResource<any> {
      get(key:string): MyAnotherInterface;
    }
    

    然后将get 函数添加为简单的(instance as any).get = (x:string)=&gt;this[x];

    【讨论】:

    • 感谢您的回复。函数get应该添加到每个对象,对吧?
    猜你喜欢
    • 2012-09-22
    • 1970-01-01
    • 2019-05-04
    • 2012-11-06
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多