You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular5中TypeScript数组类型调用报错:无调用签名无法调用

解决TypeScript Getter属性调用的签名错误问题

嘿,我一眼就看出问题啦——你把TypeScript的getter属性当成方法来调用了!

先看你写的代码:

private _locations: Array<string> = [];
constructor() { }

/**
 * Getter locations
 * @return {Array<string>}
 */
public get locations(): Array<string> {
  return this._locations;
}

/**
 * Setter locations
 * @param {Array<string>} value
 */
public set locations(value: Array<string>) {
  this._locations = value;
}

这里的locations是getter/setter属性,不是函数方法。TypeScript的getter在访问时不需要加括号,它的作用是让你像访问普通属性一样读取内部的_locations,同时可以在getter里添加额外逻辑(虽然你这里没加)。

你用this.signUpService.locations()这种带括号的方式,TS会以为你要调用一个函数,但locations的实际类型是string[],根本没有调用签名,所以才会抛出那个错误。

正确的访问方式

  • 获取值:直接当成属性访问,不用加括号
    const currentLocations = this.signUpService.locations;
    
  • 设置值:同样用属性赋值的方式
    this.signUpService.locations = ['New York', 'London'];
    

如果之后你需要在获取/设置时添加逻辑(比如过滤数据、校验值),直接在getter/setter里加就行,访问方式还是保持属性的形式,不用改调用代码,这也是getter/setter的优势之一~

内容的提问来源于stack exchange,提问作者parth.hirpara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:52:10