Typescript instantiate generic object

前端 未结 1 1114
自闭症患者
自闭症患者 2021-01-29 00:20

I have this problem, and search for hours and can\'t find the right solution for it. I\'m trying to create a generic function that revives an type and an object and convert the

相关标签:
1条回答
  • 2021-01-29 01:01

    In typescript, generic parameters are erased during the compilation and there is no trace of them in generated javascript code. So there's nothing like CreateInstance from c#.

    But, again unlike c#, classes in typescript can be used at runtime just like any other objects, so if all you need is to create an instance of a class at runtime you can do that pretty easily (note that it applies only to classes, not to any type in general).

    The syntax for generic class type argument looks a bit unusual: it's a literal type written as {new(...args: any[]): T}

    Here is complete (it compiles) example that does something like you described in your question. For simplification, I supposed that all objects that need to be instantiated must conform to common interface Result (otherwise you have to do type cast to some known type in doTheMambo to do something useful).

    interface Response { json(): any }
    
    interface Result { kind: string }
    
    function handleResult<T extends Result>(tClass: { new (...args: any[]): T }, response: Response): T {
        let jsonResp = response.json();
        let obj = jsonResp;
        let resp: T = new tClass();        
        doTheMambo(resp, obj);
        return resp;
    }
    
    class Result1 {
        kind = 'result1';
    }
    
    function doTheMambo<T extends Result>(response: T, obj: any) {
        console.log(response.kind);
    }
    
    const r: Result = handleResult(Result1, { json() { return null } });
    
    0 讨论(0)
提交回复
热议问题