Beginner’s TypeScript #25
⭐ 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
}
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.
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 = "";
}
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
➖ 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 = "";
}
}
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs/