Generic factory parameters in Typescript

后端 未结 2 1265
不知归路
不知归路 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条回答
  •  旧时难觅i
    2021-01-14 01:43

    This is what I would do:

    module Factory {
        export function createInstance(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.

提交回复
热议问题