DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #25

Image description

Error Message: "Property X Has No Initializer"

We have a User class that contains a private property named username:

class User {
    private username: string; // red squiggly line under username
}
Enter fullscreen mode Exit fullscreen mode

There is an error under username that reads:

// hovering over username shows:
Property **username** has no initializer and is not definitely assigned in the constructor.
Enter fullscreen mode Exit fullscreen mode

We will figure out how to update the User class so this error disappears.

👉 Solution

The "no initializer and not definitely assigned in the constructor" error happens because our class is not set up properly.

Initializing the Property

A straightforward way to resolve this error is to initialize the property with a value:

class User {
    private username: string = "";
}
Enter fullscreen mode Exit fullscreen mode

This assigns an initial empty string value to username.

Now if we were to create a new instance of User and attempt to access the username property, it would return an empty string as a default value:

const user = new User();
user.username; // empty string
Enter fullscreen mode Exit fullscreen mode

Assigning Value in the Constructor

Alternatively, we can assign the username property its value in the constructor of the class:

class User {
    private username?: string;

    constructor() {
        this.username = "";
    }
}
Enter fullscreen mode Exit fullscreen mode

Note that if the property has both an initializer and an assignment in the constructor, the constructor will take precedence. The value assigned in the constructor will be the property's value when we create a new class instance.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)