typescript - 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上创建了一个运行我的代码的示例,它在那里运行良好。将进行更多调查并发布我学到的东西
解决方案
推荐阅读
- scala - 选项既是函子又是单子?
- javascript - Node.js:地图功能不适用于来自 PostgreSQL 的查询
- apigee - 如何将动态 uuid 添加到 apigee 代理?
- javascript - 如何创建动态添加 html 元素的 javascript 函数?
- ios - UITableViewCell - 隐藏未使用的视图甚至不添加它们?
- python - TypeError:“条目”对象不可调用
- python - Spark 引起:java.lang.StackOverflowError 窗口函数?
- azure - Kubernetes:亲和力取决于 Azure 可用性集
- python - 你如何设计一个脚本来准备将不同数量的参数作为 argv?
- keras - Keras 层要求与摘要中不同的形状