You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报错Uncaught TypeError: Cannot set property 'version' of undefined求修复

解决 "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 to message right 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 assign message:

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:30:52