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.ts175 chars11 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.ts131 chars7 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