Do Typescript generics use type erasure to implement generics?

前端 未结 1 2027
眼角桃花
眼角桃花 2020-12-09 19:08

Meaning you cannot use something like this?

class Helpers
{
    static ObjectAs(val: any): T {
        if (!(val instanceof T)) {
            return         


        
相关标签:
1条回答
  • 2020-12-09 19:48

    The type system is wholly erased. You can see this in the generated code for any generic function.

    That said, for classes, there's still some runtime information left. You could write this:

    class A { }
    class B { }
    function As<T>(n: any, type: { new(...args: any[]): T }): T {
        if(n instanceof type) {
            return n;
        } else {
            return null;
        }
    }
    
    var x = new A();
    var y = new B();
    console.log(As(x, A));
    console.log(As(x, B));
    
    0 讨论(0)
提交回复
热议问题