Your Halloween
Your Halloween

Reputation: 9

set is not a function Typescript

I want to add objects in typescript Map and have a problem :

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

My code looks like this:

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;
    }
}

And there is simple web interface to get user's input (title and id) and add it to the Map. It looks like this:

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

Could you please help me to find the error?

Upvotes: 0

Views: 4449

Answers (1)

hackerrdave
hackerrdave

Reputation: 6706

Your constructor is defining this.things to be an empty object, which does not have a function set defined. You would need to initialize a new Map() instead:

things: Map

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

Upvotes: 4

Related Questions