【问题标题】:How to implement array signature method in typescript如何在打字稿中实现数组签名方法
【发布时间】:2013-02-09 21:00:50
【问题描述】:

尝试编译:

interface ListInterface {
    getObject(index: number): Object;
    [index: number]: Object;
}

class List123 implements ListInterface {
    private list: Object[] = [1,2,3];
    getObject(index: number) { return this.list[index] }
    [index: number] { return this.getObject(index) }
}

但 tsc 正在发射:

[ ] 方法声明的类定义中出现意外的“[”。

Typescript Playground Link(取消注释 //? 我遇到的问题)

【问题讨论】:

    标签: typescript


    【解决方案1】:

    有些类型注解用于定义 JavaScript 行为,但无法实现 - 索引器注解就是这样一个例子。

    请参考related discussion on codeplex

    对于问题中提供的代码示例,有一个部分解决方案,因为 JavaScript 对象自然支持索引器表示法。因此可以这样写:

    interface ListInterface {
        getObject(index: number): Object;
    }
    
    class List123 implements ListInterface {
    
        getObject(index: number) { 
            return <Object> this[index] 
        }
    }
    
    var list  = new List123();
    list[1] = "my object";
    
    console.log(list[1]); // "my object"
    console.log(list.getObject(1)); // "my object";
    

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 2017-05-03
      • 2018-04-19
      • 1970-01-01
      • 2017-01-17
      • 2020-06-27
      • 1970-01-01
      • 2021-04-12
      相关资源
      最近更新 更多