【问题标题】:New function constructor that returns another function in TypeScript在 TypeScript 中返回另一个函数的新函数构造函数
【发布时间】:2021-12-29 15:43:58
【问题描述】:

我在 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"))

On TS Playground

【问题讨论】:

    标签: typescript


    【解决方案1】:

    为什么要在返回函数的东西上使用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();
    

    Live Example

    我认为这是你应该使用的。话虽如此,指定构造函数返回什么的能力 is not yet available 但将来可能会实现。

    我可以建议一个解决方法(来自上面的链接问题)或this answer,但我不明白你为什么要在你的情况下使用它,因为我的建议更简单,而且这里不需要课程.

    【讨论】:

    • 我想我真的不需要,我只是习惯使用this。谢谢
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-03-23
      • 2013-10-03
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 2010-09-15
      相关资源
      最近更新 更多