5

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;
}

This gives error:

Duplicate identifier 'searchFilter'.

I'm using TypeScript in an Angular project.

@angular/cdk: 6.0.1
@angular/cli: 1.7.4
typescript: 2.5.3
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
sander
  • 1,426
  • 4
  • 19
  • 46

1 Answers1

10

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

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;
}
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Does adding _ in front of field make it automatically private or do you have to explicitly type private _variableName? – sander May 10 '18 at 13:29
  • 3
    No its just a convention – yurzui May 10 '18 at 13:29
  • 2
    The linter is likely to give you a warning on using `_` – pronebird Jun 24 '18 at 10:00
  • 2
    @sander It does not make the variable private, and it should be noted that it's a convention that goes against [Angular guidelines](https://angular.io/guide/styleguide#properties-and-methods). – Standaa - Remember Monica Mar 01 '19 at 10:15
  • 1
    using _ is not a convention it is a bad practice..so this works but is not really a solution – Julius Koronci Sep 18 '19 at 11:21
  • @JuliusKoronci If it is not a convention and is a bad practice for you it doesn't mean that it is a bad practice for all. Take a look at Angular material source code https://github.com/angular/components/blob/20019655dfdab44901590643bac72d955f1dff1c/src/material/table/table-data-source.ts#L85-L90 – yurzui Sep 18 '19 at 13:11
  • well take a loot at airbnb..there is a huge discussion about how it is a bad practice to try to say that something is private when in fact it is not and people misuse it..once you change your private api and someone used the method, his code starts breaking. It was a convention very long time ago but the world moved forward :) .. – Julius Koronci Sep 20 '19 at 08:57
  • People are arguing against it but not providing alternatives. I don't see a more straightforward way to handle duplicate identifiers. How would others name their internal `searchFilter` attribute and the setter/getter? I don't particularly like `_` but I can deal with it. – Damien Roche Jun 08 '20 at 12:47