Typescript – set default value for class members

Yes, easily, and you don’t need to add a class constructor.

export class Profile extends ServerData {
  name: string;
  email: string;
  age: number = 0;
}

The ability to define default values is one of the main things that differentiates a class from an interface.

For this to work you need to call new Profile() somewhere in your code, otherwise a class instance won’t be created and you won’t have defaults set, because the above TypeScript will compile to the following JavaScript:

var Profile = /** @class */ (function () {
    function Profile() {
        this.age = 0;
    }
    return Profile;
}());

So just using it for type assertion at compile-time isn’t sufficient to set a default at run-time.

See it in action in the TypeScript Playground.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)