我想在typescript Map中添加对象并遇到问题:
TypeError:this.things.set不是函数。
我的代码如下所示:
Thing.ts:
export class Thing {
id: string;
title: string;
constructor(id, title) {
this.title = title;
this.id = id;
}
getID(){
return this.id;
}
}
Robot.ts
export class Robot {
things = new Map<string, Thing>();
constructor() {
this.things = {};
}
public addThing(t: Thing) {
this.things.set(t.id, t);
}
public showThings(){
return this.things;
}
}
还有简单的Web界面来获取用户的输入(标题和ID)并将其添加到Map。它看起来像这样:
Index.ts
let r: Robot = new Robot();
//...
app.get("/api/newThing", (req, res) => {
if (req.query.id === undefined | req.query.title === undefined) {
res.status(400);
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end("error here");
} else {
console.log(req.query.id, req.query.title);
r.addThing(req.query.id, new Thing(req.query.id, req.query.title));
res.send("Thing is added. Disconnection...");
console.log(r.showThings());
}
}
你能帮我找一下这个错误吗?
答案 0 :(得分:3)
您的构造函数将this.things
定义为空对象,该对象没有定义函数set
。您需要初始化new Map()
而不是:
things: Map
constructor() {
this.things = new Map()
}