TypeScript报错Uncaught TypeError: Cannot set property 'version' of undefined求修复
Hey there, let's break down what's causing this error and fix it right away.
The root issue here is that even though you've declared the message property in your API class, you never initialized it with an actual object. So when you try to set this.message.version, this.message is still undefined—you can't access a property on something that doesn't exist yet!
Here's your original code that's throwing the error:
class API { private message: { version: string, success: boolean }; public version() { this.message.version = "1.0"; console.log(this.message); } } let apiObj = new API(); apiObj.version();
Two simple fixes to solve this:
Initialize the property when declaring it
Assign a default object tomessageright where you declare it. This ensures it's ready to use as soon as the class is instantiated:class API { private message: { version: string, success: boolean } = { version: "", success: false }; public version() { this.message.version = "1.0"; console.log(this.message); // Output: { version: "1.0", success: false } } } let apiObj = new API(); apiObj.version();Initialize in the constructor
If you prefer to set up the object when the class is created, use the constructor to assignmessage:class API { private message: { version: string, success: boolean }; constructor() { // Initialize the message object here this.message = { version: "", success: false }; } public version() { this.message.version = "1.0"; console.log(this.message); } } let apiObj = new API(); apiObj.version();
Either approach will make sure this.message is a valid object before you try to update its version property, eliminating that TypeError entirely.
内容的提问来源于stack exchange,提问作者Thavaprakash Swaminathan

