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

TypeScript接口方法变量无法解析,报错TS2304:找不到firstName

问题解决:TS2304: Cannot find name 'firstName'

错误原因

getFullName使用箭头函数时,箭头函数不会绑定自身的this,而是继承外层作用域的this;同时直接写firstName会被当作全局变量,而非当前对象的属性,因此TypeScript无法找到该变量。

解决方案

将getFullName的箭头函数改为普通函数,此时函数内部的this会指向当前的IDoctor对象,即可正常访问firstName和lastName属性。

修改后的完整代码:

export enum Gender {
  Male,
  Female
}

export interface IPerson {
  id: number;
  firstName: string;
  lastName: string;
  getFullName: () => string;
  gender: Gender;
}

export interface IDoctor extends IPerson {
  doctorNo: number;
}

const testUser: IDoctor[] = [
  {
    id: 1,
    firstName: "a",
    lastName: "aa",
    getFullName: function() {
      return `Doctor First & Last Name: ${this.firstName} ${this.lastName}`;
    },
    gender: Gender.Male,
    doctorNo: 1
  },
  {
    id: 2,
    firstName: "b",
    lastName: "bb",
    getFullName: function() {
      return `Doctor First & Last Name: ${this.firstName} ${this.lastName}`;
    },
    gender: Gender.Female,
    doctorNo: 2
  }
];  

console.log("First Doctor", testUser[0].getFullName());

补充说明

  • 原代码未定义Gender枚举,已补充至代码中,避免额外报错。
  • 若坚持使用箭头函数,需通过对象引用访问属性,但这种写法灵活性差,不推荐:
    {
      id: 1,
      firstName: "a",
      lastName: "aa",
      getFullName: () => `Doctor First & Last Name: ${testUser[0].firstName} ${testUser[0].lastName}`,
      gender: Gender.Male,
      doctorNo: 1
    }
    

内容的提问来源于stack exchange,提问作者Karim Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:10:25