add a public property to a class in typescript

To add a public property to a class in TypeScript, you can simply define a property at the class level and prefix it with the public access modifier. Here is an example:

index.ts
class Person {
  public name: string;
  
  constructor(name: string) {
    this.name = name;
  }
}

let person = new Person("John");
console.log(person.name); // Output: John
175 chars
11 lines

In the above code, a public property called name is added to the Person class. The constructor takes a parameter called name, which is assigned to the name property of the class using the this keyword. The public keyword before the property name allows it to be accessed from outside of the class.

You can also define public properties using a shorthand syntax in the constructor parameters. Here is an example:

index.ts
class Person {
  constructor(public name: string) {}
}

let person = new Person("John");
console.log(person.name); // Output: John
131 chars
7 lines

In the above code, the name property is defined in the constructor parameter list with the public access modifier. This creates a public property called name and assigns the constructor parameter value to it. This syntax is shorter and more concise than the previous example.

gistlibby LogSnag