Generic factory parameters in Typescript

后端 未结 2 1244
不知归路
不知归路 2021-01-14 01:01

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

function create         


        
相关标签:
2条回答
  • 2021-01-14 01:30

    You can't define a single factory method that can pass an arbitrary number of parameters to the constructor of an arbitrary class.

    You can, however, define a factory method for any specific number of constructor parameters. Here's a rather elaborate sample in the Typescript playground. It defines classes and interfaces and derived classes and interfaces and then uses them to demonstrate the factory method working.

    Line 38 of the example is probably the most interesting and impressive part of the whole show: an incompatible parameter is specified and this is statically detected by the editor! By implication line 38 has passed the same check, and this matches expectation; Wobble is a derivative of Wibble and therefore acceptable, and the parameter is declared as IRaw2 which is a derivative of the declared parameter type of IRaw1, and therefore also acceptable.

    If you wanted a two-parameter constructor it would look like this:

    export function createInstance<T1, T2, T3>(ctor: new(p: T1, q: T2) => T3, p:T1, q:T2): T3 {
      return new ctor(p, q);
    }
    
    0 讨论(0)
  • 2021-01-14 01:43

    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.

    0 讨论(0)
提交回复
热议问题