Reputation: 485
Is there a way to use a method as a property in TypeScript?
Like, for example, in Python @property
decorator
Upvotes: 0
Views: 824
Reputation: 1075547
You can use an accessor property, like this:
class Example {
get name(): string {
return "Fred";
}
}
Example on the TypeScript playground
That's an accessor property that only has a getter. You can also define a setter:
class Example {
private _name: string = "";
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
}
}
(You don't have to store the value in a TypeScript-style private member, that's just an example.)
Technically, you can have an accessor with a setter and no getter (a write-only property).
Upvotes: 4