what is new() in Typescript?

后端 未结 3 684
一生所求
一生所求 2020-12-07 18:14

I encountered new() in the official document here about generics.

Here is the code context:

function create(c: { new(): T; } )         


        
3条回答
  •  暖寄归人
    2020-12-07 18:40

    The new keyword is used to create an instance of a class, so in it's simplest form:

    class SimpleClass {
    }
    

    Would be constructed as follows:

    let simpleClassInstance = new SimpleClass();
    

    This is all well and good, but how do you create an instance of a generic class, i.e:

    class SimpleClassFactory< T > {
        static create( T ) {
            return new T(); // compile error could not find symbol T
        }
    }
    

    Would be used as follows:

    let simpleClassInstance = SimpleClassFactory.create(SimpleClass);
    

    Here, we are attempting to use the class definition to create an instance of a class. This will generate a compile error.

    So we need to refer to the type by it's constructor signature:

    class SimpleClassFactory< T > {
        static create( type: { new(): T ;} ) {
            return new type(); // succeeds
        }
    }
    

提交回复
热议问题