Avoid initializing every variable inside class's constructor

Viewed 41

I have many models ( which are javascript classes ) holding names for my database, and also it's types. Is there a way I can create a new User without having to call all those attributes inside the constructor ?

class User {
    name: string;
    email: string;
    password: string;

    constructor(values: User) {
        this.name = values.name;
        this.email = values.email;
        this.password = values.password;

        // I don't want to call this.name, this.email, ... Since this User model is relatively small, but I have models with hundreds of attributes
    }
}
1 Answers

In typescript you can create class fields in the constructor's argument list, like this:

class User {
    // nothing here :)
    constructor(private name: string, private email: string, private password: string) {
        // empty :)
    }
}

If you specify an access modifier, you get the declaration and the assignment automatically.

Related