重复声明TypeScript Getter Setter [英] Duplicate declaration TypeScript Getter Setter

查看:134
本文介绍了重复声明TypeScript Getter Setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为TypeScript中的字段创建一个吸气剂和吸气剂.

I'm trying to create a getter and setter for a field in TypeScript.

searchFilter: string;

get searchFilter(): string {
  return this.searchFilter;
}

set searchFilter(value: string) {
  this.searchFilter = value;
}

这会导致错误:

Duplicate identifier 'searchFilter'.

我在Angular项目中使用TypeScript.

I'm using TypeScript in an Angular project.

@angular/cdk: 6.0.1
@angular/cli: 1.7.4
typescript: 2.5.3

推荐答案

您不能拥有与用于getter或setter的名称相同的属性.

You can't have property with the same name you used for getter or setter.

因此创建另一个私有属性(_searchFilter)来存储本地状态

So create another private property(_searchFilter) to store local state

private _searchFilter: string;

get searchFilter(): string {
  return this._searchFilter;
}

set searchFilter(value: string) {
  this._searchFilter = value;
}

这篇关于重复声明TypeScript Getter Setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆