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:
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);