What is new() => T?
Essentially it is a way to declare an "Object Type" in which you can then create an instance of said "Object Type" with.
Example
class MyClass {
// ...
}
// Creates new object types that don't have arguments in their constructors
function createObjectGivenObjectType<T>(ObjectType: new() => T): T {
return new ObjectType();
}
const myObject: MyClass = createObjectGivenObjectType(MyClass);
Simplify new() => T
I personally find it confusing when I see new() => T in a codebase. To simplify the problem, and to allow for better code readability, abstract this idea away from other devs by declaring a new type in your codebase called Type
:
export type Type<T> = new (...args: any[]) => T;
Then the above createObjectGivenObjectType
function can become:
// Then this reads as: ObjectType is a type of T
function createObjectGivenObjectType<T>(ObjectType: Type<T>): T {
return new ObjectType();
}
Furthermore, what does { new(): T; } mean? I know it must be a type, but how?
From the example you give it appears to be a more obtuse way of passing in an "Object Type" to a function.
Some examples that all do the same thing:
function create<T>(c: { new(): T; }): T {
return new c();
}
create(X);
function create<T>(c: new() => T): T {
return new c();
}
create(X);
function create<T>(c: Type<T>): T {
return new c();
}
create(X);