TS 对象声明
TS object declaration
我是 typescript 和 javascript 的新手,我想将 JS
中的这段代码转换为其 TS
版本。当我尝试访问打字稿版本中的 this
对象时,它说 'this possibly be 'unknown'
或类似的东西。
你能帮我理解你是如何在 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
试试这个方法:
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');
我是 typescript 和 javascript 的新手,我想将 JS
中的这段代码转换为其 TS
版本。当我尝试访问打字稿版本中的 this
对象时,它说 'this possibly be 'unknown'
或类似的东西。
你能帮我理解你是如何在 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
试试这个方法:
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');