Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is new() in Typescript?

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?

like image 271
Nicolas S.Xu Avatar asked Sep 21 '16 17:09

Nicolas S.Xu


People also ask

What does New do in TypeScript?

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

What is the use of new keyword?

The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.

What is new function in JavaScript?

New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.

How do I create a new object in TypeScript?

Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.


1 Answers

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}

like image 155
Nahush Farkande Avatar answered Sep 28 '22 06:09

Nahush Farkande