Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  103] [ 6]  / answers: 1 / hits: 26411  / 8 Years ago, wed, september 21, 2016, 12:00:00

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



Here is the code context:



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


The above code is transpiled to the following JavaScript code:



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


new() is illegal syntax in JavaScript. What does it mean in TypeScript?



Furthermore, what does {new(): T; } mean? I know it must be a type, but how?


More From » typescript

 Answers
15

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<T>(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<T>(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}


[#60649] Sunday, September 18, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marques

Total Points: 366
Total Questions: 108
Total Answers: 111

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
marques questions
;