【问题标题】:returntype Promise<this>返回类型承诺<this>
【发布时间】:2017-01-26 05:01:04
【问题描述】:

我知道打字稿supports return type this。这可能是我需要的,除了我有一个静态方法,它返回定义它的类的实例或它的子类。所以我尝试使用:

class A {
    static createInstance(resource):Promise<this> //<---what can I put here??
    {
        //pseudo code: load a module, async
        return loadModule(resource.module).then(() => {
            //find Class from resource data, can return A, or B or any subclass
            var targetClass = resource.getType().getClass();
            //create instance of A or any subclass of A
            return new targetClass.prototype.constructor();
        }
    }
}
//module B.js which is loaded on demand:
class B extends A {
    //I dont want to have to overwrite the returntype of createInstance
    //in every subclass of A
}

Promise&lt;this&gt; 不起作用。 Promise&lt;typeof this&gt; 也没有。有没有其他方法可以做我想做的事?

【问题讨论】:

  • 您介意提供一些来自周围代码的上下文吗?通常这样的方法是静态的。
  • 是的,你是对的,我实际使用的方法是静态的。我用我正在尝试做的事情更新了代码

标签: typescript types this


【解决方案1】:

返回this时,必须返回当前实例。
由于该实例已经存在,因此您无需向其返回 Promise

如果你想将Promise返回到this的子类,那么这意味着你并不是真的想返回this,而是this类的子类的实例,即不是这个功能的目的。

考虑以下代码:

class A {
    x: number = 0;

    add(y: number): this {
        this.x += y;
        return this;
    }

    sub(y: number): this {
        this.x -= y;
        return new B() as this;
    }
}

class B extends A { }

let a1 = new A();
console.log(a1.add(3).add(5).x); // 8

let a2 = new A();
console.log(a2.add(3).sub(2).x); // 0

第二个console.log 应该基于“构造”打印1 而不是0,因为返回this 应该总是返回当前实例.


编辑

目前没有办法做到这一点。
有一个未解决的问题:Polymorphic "this" for static members,他们的示例几乎就是您想要做的。


第二次编辑

必须返回当前实例,而不仅仅是“这个类”的一个实例,一个简单的例子:

class A {
    fn1(): this {
        return this;
    }

    fn2(): this {
        return new A(); // Error: Type 'A' is not assignable to type 'this'
    }
}

(code in playground)

【讨论】:

  • 好的,我知道this 可能无法使用。 Tnx 用于澄清示例。我已经使我的示例代码更完整,以解释我想要做什么,你知道我如何可以为这个示例定义返回类型吗?
  • 在您更新的示例中,资源参数应确定类型。您可以通过根据resource 参数的类型重载函数声明来实现此目的。例如,您可以使用字符串文字类型。
  • "返回这个时你必须返回当前实例。"这是不正确的。 this 类型只是意味着它与目标实例的类型相同。
  • 查看我修改后的答案。 @AluanHaddad 这确实是正确的,如果您的返回类型是this,那么您必须返回确切的实例,检查构建器模式以了解原因。
  • @AluanHaddad 这是强制性的。检查我对答案的第二次编辑
【解决方案2】:

怎么样:

static createInstance<T>(resource): Promise<T>

【讨论】:

  • 啊是的,这是一种可能性,但是我会输入B.createInstance&lt;B&gt;(resource).then(b =&gt; ...),这与我现在所拥有的没有太大区别:B.cteateInstance(resourse).then((b:B) =&gt; ...) .. 我问这个问题,看看我是否可以摆脱在这个经常使用的命令中输入两次B
猜你喜欢
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2019-04-25
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 2015-11-27
相关资源
最近更新 更多