what is new() in Typescript?

后端 未结 3 681
一生所求
一生所求 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:21

    new() describes a constructor signature in typescript. What that means is that it describes the shape of the constructor. For instance take {new(): T; }. You are right it is a type. It is the type of a class whose constructor takes in no arguments. Consider the following examples

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

    What this means is that the function create takes an argument whose constructor takes no arguments and returns an instance of type T.

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

    What this would mean is that the create function takes an argument whose constructor accepts one number a and returns an instance of type T. Another way to explain it can be, the type of the following class

    class Test {
        constructor(a: number){
    
        }
    }
    

    would be {new(a: number): Test}

提交回复
热议问题