TypeScript return object constructed form generic

前端 未结 1 399
有刺的猬
有刺的猬 2021-01-25 02:35

I\'d like to define following generic function to process conversion from interface type to class type implementing this interface. Consider following interface/class pair:

1条回答
  •  孤街浪徒
    2021-01-25 03:22

    The problem is that O does not exist at runtime (generics are erased at runtime in typescript), and at runtime you need to use O to instantiate the new class. You need to pass the actual constructor to the function:

    function fromInterfaceToObject(iIn: I, o: new (iIn: I) => O): O {
        return new o(iIn);
    }
    
    fromInterfaceToObject({ num: 10 }, Example);
    

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