0

I'm new to typescript and javascript, and I want to convert this code in JS to its TS version. When I try to access this object in the typescript version, it says that 'this possibly be 'unknown' or something like that. Could you please help me to understand how you implement this code in TS?

const singleton = {

    instance: null, // socket.io instance

    getInstance: (server) => {
        if (!this.instance) {
            this.instance = server; // takes 'Hello' as the value
        }
        return this.instance;
    },

}

let a = singleton.getInstance('Hello');
let b = singleton.getInstance('World');

console.log(a === b); // true
console.log(a); // Hello
console.log(b); // Hello
  • 1
    Try rewrite function from arrow notation to usual. – capchuck Aug 29 '21 at 12:34
  • Thanks, its works but why? An arrow function is an object by itself? – Ali Naderi Parizi Aug 29 '21 at 12:43
  • It works because arrow functions as an object property have no reference of this, they have no binding by default. Still you could get it work if you'd use `let a = singleton.getInstance.call(singleton, 'Hello');` More about it you can learn from [here](https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/) – capchuck Aug 29 '21 at 12:47
  • It is all about `function context` :) – capchuck Aug 29 '21 at 12:49
  • Good you're converting this to Typescript - you just got the compiler find a bug in your Javascript implementation! – Bergi Aug 29 '21 at 14:51
  • Yeah, that's it. Arrow functions as object methods do not inherit `prototype` reference in `this`. In order to access `prototype` of the object using `this` you need to use ES3 style function (`function () {}`) or simply `{ myFunc() {} }` when inside object literal or class – SrHenry Aug 29 '21 at 15:54

1 Answers1

-1

Try this approach:

class Singleton {

    static instance = null; // socket.io instance

    static getInstance(server) {
        if (!Singleton.instance) {
            Singleton.instance = server; // takes 'Hello' as the value
        }

        return Singleton.instance;
    }

}

let a = Singleton.getInstance('Hello');
let b = Singleton.getInstance('World');
  • Thanks, but I wanted an object, not a class. – Ali Naderi Parizi Aug 29 '21 at 13:01
  • No, do not use a `class` with only static methods. – Bergi Aug 29 '21 at 14:51
  • @Bergi My guess is that this is just an example of the code and Ali will add an implementation of it later. Otherwise, it can be just a simple function that keeps an instance encapsulated in const. I think keeping singleton inside an object is useless. – Oleksandr Karpov Sep 02 '21 at 09:32
  • @okarp Yes, it should just be a simple function, and I agree that singletons are mostly useless in general :-) (What's worse though is that if `getInstance` takes the instance as a parameter, it isn't even a singleton pattern) – Bergi Sep 02 '21 at 12:12