【问题标题】:Typescript does not know about Array.map打字稿不知道 Array.map
【发布时间】:2015-08-10 18:10:12
【问题描述】:

我怀疑我犯了一个错误,但我无法让以下内容通过类型检查。我最终得到Property 'map' does not exist for type 'Restos'。我已经按照TS教程设置了界面,所以感觉好像map没有默认包含(我在tsconfig中有"target": "es6"

interface Resto {
    rname:String,
    qname:String,
    tel:String
}

interface Restos {
    [index:number]:Resto;
}

class MainController {
    headline: String;
    rnames: [String];

    constructor($http : ng.IHttpService) {
        this.headline = "hello world";

        $http.get('http://afbackend.herokuapp.com/api/restos')
        .success( (res:Restos) => {
            console.log(res);
            this.rnames = res.map(r => r.rname)
                              ^^^ 
        });
    }
}

【问题讨论】:

  • 在您的 Restos 界面中,map 方法在哪里?也许只是使用 Resto[] 而不是 Restos。

标签: typescript


【解决方案1】:

编译器唯一知道的关于Restos 的事实是,当您使用number 对其进行索引时,您会得到Resto。仅仅因为某事物具有数字索引签名并不意味着它是一个数组(例如,对象{0: 'hello', 1: 'world'} 可以按数字索引以生成字符串,但您不能在其上调用.map)。

你可能想写的是type Restos = Array<Resto>而不是界面。

【讨论】:

  • 干杯 - 我用Interface 把它弄得太复杂了,type 做到了。 type Restos = Resto[] 也有效。 (是的,我知道 [String] 也错了)。在我的辩护中,我会注意到type 语法没有在typescriptlang.org/Handbook 中提及
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 2016-02-28
  • 2020-01-14
  • 1970-01-01
  • 2020-12-26
  • 2018-06-13
  • 2022-06-29
相关资源
最近更新 更多