首页 > 解决方案 > TypeError...不是一个函数

问题描述

我有一个User带有toJSON函数的简单类

class User {
  username: string;
  photoUrl: string;

  constructor(username: string, photoUrl: string) {
    this.username = username;
    this.photoUrl = photoUrl;
  }

  toJSON(): any {
    let json = {
      username: this.username,
      photoUrl: this.photoUrl,
    };
    return json;
  }
}

另一个Notification具有自己的toJSON函数的类试图调用User.toJSON但我得到运行时错误TypeError: user.toJSON is not a function

class Notification {
  users: User[]
  
  constructor(
    users: User[],
  ) {
    this.users = users
  }

  addUser(user: User) {
    console.log(">>> adding user ", user.toJSON())
    this.users.push(user)
  }

  toJSON(): any {
    const usersJSON: any = [];
    this.users.forEach((user: User) => {
      usersJSON.push(user.toJSON())
    // swapping the line above with the line below works fine
    //usersJSON.push({ username: user.username, photoUrl: user.photoUrl });
  })

  let json = {
    users: usersJSON,
  };

  return json
}

奇怪的事情(对我来说)是 toJSON 调用在其他地方工作正常,它只是在Notification.toJSON?

编辑

在typescriptlang.org上创建了一个运行我的代码的示例,它在那里运行良好。将进行更多调查并发布我学到的东西

标签: typescript

解决方案


推荐阅读