在TypeScript中返回另一个函数的新函数构造函数



我在JavaScript中有这个函数:

function test()
{
this.list = {};
return (id) =>
{
if (!(id in this.list))
this.list[id] = {default: 123};
return this.list[id]
}
}
const blah = new test();
blah("ok").mykey = "ok";
console.log(blah("ok").mykey);
console.log(blah("ok"));

我正在尝试将其转换为TypeScript格式。我知道我必须使用class,但是我如何从类构造函数返回函数?

我不想有一个额外的属性myfunc作为函数new test().myfunc("ok"):

interface simpleObject
{
[key:string]: string|number|object;
}
class Test
{
private list:simpleObject;
public myfunc(id:string)
{
if (!(id in this.list))
this.list[id] = {default: 123};
return this.list[id] as simpleObject;
}
constructor()
{
this.list = {};
}
}
const blah = new Test();
blah.myfunc("test").mykey = "ok";
console.log(blah.myfunc("test").mykey);
console.log(blah.myfunc("test"))

TS游乐场

为什么要在返回函数的东西上使用new?只需调用不带new的函数即可。

您可以通过将状态保持在闭包中而不是使用this来实现这一点;

function test() {
const list: {[id: string]: any} = {};
return (id: string) =>  {
if (!(id in list)) {
list[id] = {default: 123};
}
return list[id]
}
}
const blah = test();

参见的实际示例

我认为这是你应该使用的。话虽如此,指定构造函数返回内容的能力还不可用,但将来可能会使用。

我可以建议一个变通方法(来自上面的链接问题(或这个答案,但我不明白你为什么要在你的案例中使用它,因为我建议的更简单,而且这里不需要类。

类的构造函数将返回所述类的实例,这就是预期行为。您的用例实际上并不需要使用类。你仍然可以拥有你的功能,并在里面使用this。要告诉TypeScriptthis是什么类型,可以使用一个保留参数:

type ReturnedFunction = (id: string) => string | number | object;
type TestFunction = () => ReturnedFunction;
function test(this: TestFunction): ReturnedFunction {
// same code as before
}

最新更新