Here is a thing, in Typescript there is a shorthand to create and assign class properties from constructor params.
Imagine you have following code, let’s say you have class User
:
class User {
private name: string;
private surname: string;
private age: number;
constructor(name: string, surname: string, age: number) {
this.name = name;
this.surname = surname;
this.age = age;
}
}
You can write same class using shorter syntax:
class User {
constructor(
private name: string,
private surname: string,
private age: number
) {}
}
In this case Typescript
will automatically generate thore properties. And yes both definitions will produce same Javascript code:
var User = /** @class */ (function() {
function User(name, surname, age) {
this.name = name;
this.surname = surname;
this.age = age;
}
return User;
})();
And it works not only for private
access level modifier, you can use public
or protected
as well.
So you can use this constructor assignment technique to save some lines of code.
Top comments (6)
This article was one of the top hits when I was searching for this concept, but I couldn't figure out the official term for this shorthand; turns out it's called "parameter properties", and the official documentation for them is at typescriptlang.org/docs/handbook/2....
Exactly what brought me here: trying to figure out the name of this feature. Kudos for using language I thought to search for.
Daaaaang. You know, I generally tend to stay away from classes because I prefer to separate data from logic (you know, “functional programming” style), but sometimes it’s really convenient to use a class for encapsulating a set of shared functions (like a date class). So this is really helpful. Thank you! :)
Glad to be helpful :)
Hi, i wonder if you can add exempel shorthand for interface with readonly property. I am having problem.
interface abcd {
readonly x: number;
y: string;
}
class xyz extends abcd {
constructor (readonly x,
y:string=''){}
}
**** when i declare new xyz() says expect 2 parameters, shorthand does not work in this case.
Thanks for a concise explanation!