Typescript中的通用工厂参数 [英] Generic factory parameters in Typescript

查看:88
本文介绍了Typescript中的通用工厂参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自官方Typescript文档的一个通用工厂的示例。
$ b

  function create< T>(c:{new():T;}在这个示例中,构造函数不接受参数。 ):T {
return new c();
}

我怎么可以重写这个,除了一个类型,工厂方法接受其他参数并在它调用正在实例化的类的构造函数时传递它们?所以return语句看起来像这样:

  return c(p1,p2); 

我不清楚的是这个

  {new():T; } 

实际上是一个接口,因为它定义了所提议的类的兼容性的评估条件,顺便也声明构造函数签名。我将回答我自己的问题。

解决方案

这就是我要做的:

  module Factory {
导出函数createInstance< T扩展Wibble,K扩展IRaw1>(ctor:{new(raw:K):T} :K):T {
return new ctor(data);
}
}
var raw1 = {Foo:foo}作为IRaw1;
var d1 = Factory.createInstance(Wibble,raw1);

var raw2 = {Foo:foo,Bar:bar}作为IRaw2;
var d2 = Factory.createInstance(Wobble,raw2);

如果您的构造函数需要更多参数,那么只需将它们添加到传递给ctor,这样你就不需要为每个参数添加更多的通用约束。

This is the sample from the official Typescript documentation for a generic factory. In this sample the constructor does not take parameters.

function create<T>(c: {new(): T; }): T {
  return new c();
}

How could I rewrite this so that in addition to a type, the factory method accepts other parameters and passes them when it invokes the constructor of the class it is instantiating? So the return statement would look something like this:

return c(p1, p2);

Something that wasn't clear to me is that this

{new(): T; }

is effectively an interface, inasmuch as it defines the terms of assessment for compatibility of a proposed class, incidentally also declaring the constructor signature. I'm going to answer my own question.

解决方案

This is what I would do:

module Factory {
    export function createInstance<T extends Wibble, K extends IRaw1>(ctor: { new (raw: K): T }, data: K): T {
        return new ctor(data);
    }
}
var raw1 = { Foo: "foo" } as IRaw1;
var d1 = Factory.createInstance(Wibble, raw1);

var raw2 = { Foo: "foo", Bar: "bar" } as IRaw2;
var d2 = Factory.createInstance(Wobble, raw2);

If your constructors need more arguments, then just add them to the one object you're passing to the ctor, this way you won't need to add more generic constraints per argument.

这篇关于Typescript中的通用工厂参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆