gpt4 book ai didi

javascript - set 不是函数 Typescript

转载 作者:行者123 更新时间:2023-11-28 17:44:49 24 4
gpt4 key购买 nike

我想在 typescript Map 中添加对象,但遇到问题:

TypeError: this.things.set is not a function.

我的代码如下所示:

Thing.ts:

export class Thing {
id: string;
title: string;

constructor(id, title) {
this.title = title;
this.id = id;
}
getID(){
return this.id;
}
}

机器人.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 中。它看起来像这样:

索引.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());
}
}

您能帮我找出错误吗?

最佳答案

您的构造函数将 this.things 定义为一个空对象,该对象没有定义函数 set。您需要初始化一个new Map():

things: Map

constructor() {
this.things = new Map()
}

关于javascript - set 不是函数 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47003076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com