TypeScript getter setter convention

12,087

Java is a statically compiled language. In Java, if you publish a .jar library with a class

class Foo {
  public int bar;
}

and later decide to introduce a logic around that field

class Foo {
  private int _bar;
  public int getBar() { return _bar - 1; }
  public void setBar(int v) { _bar = v + 1; }
}

any code that uses your .jar will break and will have to be updated and re-compiled. This is why it's a big no-no in Java to expose raw public fields.

TypeScript is a superset of JavaScript which is a dynamic language. All linking is dynamic. You can safely release a library with a class

class Foo {
  bar: number
}

If you later release an update

class Foo {
  private _bar: number
  get bar() { return this._bar - 1 }
  set bar(v: number) { this._bar = v + 1 }
}

your library users won't notice.

Share:
12,087
Joshua
Author by

Joshua

Updated on November 30, 2022

Comments

  • Joshua
    Joshua 11 months

    What is the convention (standard) in TypeScript for class attributes?

    In the angular 2 demo (The Heroes Tour from angular.io) all attributes are set to public :

    export class Hero {
       id: number;
       name: string;
    }
    

    So they can be instanciated both ways :

    var hero: Hero = new Hero();
    hero.id = 0;
    hero.name = "hero";
    

    or

    var hero2: Hero = {id : 0, name: "hero"};
    

    Is there a Java style convention (like this) :

    export class Hero {
       private id: number;
       private name: string;
    
       setId(id: number): Hero {
          this.id = id;
          return this;
       }
    
       setName(name: string): Hero {
          this.name = name;
          return this;
       }
    
       getId(): number {
          return this.id;
       }
    
       getName(): string {
          return this.name;
       }
    }
    

    Declaration (exemple) :

    var hero: Hero = new Hero();
    hero.setId(0).setName('hero');
    
    var hero2: Hero = new Hero().setId(0).setName('hero');
    
  • Laurent Schwitter
    Laurent Schwitter almost 6 years
    Nobody forbids you from doing that but it's not the convention and it's overdeclarative and can get pretty ugly very quickly
  • Marty
    Marty about 4 years
    This approach actually answers the OP's question and is accurate with a reasonable caution, and is referenced in the TypeScript docs typescriptlang.org/docs/handbook/classes.html#accessors