Typescript constructor: new vs class vs typeof class

Viewed 111

In Typescript, what is the difference between types T1-T4:

class MyClass {
}

type T1 = MyClass;
type T2 = typeof MyClass;
type T3 = new () => MyClass;
type T4 = { new(): MyClass };

Intellisense shows me different options but I can't tell what they actually point to.

Is there a difference between T2, T3, and T4 since the following works:

const t1: T1 = new MyClass();
const t2: T2 = MyClass;
const t3: T3 = MyClass;
const t4: T4 = MyClass;
1 Answers

typeof is a way to refer to the type of a value. Example:

let s = 'Hello'
let n: typeof s;

n would be type string. Link to typescript docs about typeof

Looking at the JavaScript output from the TypeScript and using console.log on the variables, T2, T3 and T4 end up containing the constructor function for MyClass, i.e.: function MyClass() {}. The TypeScript you wrote boils down to references to the MyClass constructor function I believe.

Hopefully that helps.

Related