Constructor functions
Constructor functions are special functions used to create and initialize objects.
They are most commonly associated with classes, but you can also use them with plain functions to create instances of objects.
function Person(name: string, age: number) {
this.name = name;
this.age = age;
}
const person = new Person("Bob", 25)
console.log(person.name)
console.log(person.age)
Constructor signature
A constructor signature is the type definition of a constructor function. This allows you to define the types of the parameters that the constructor function accepts.
type PersonConstructor = new (name: string, age: number) => Person;
class Person {
constructor(public name: string, public age: number) {}
}
const createPerson: PersonConstructor = Person;
const newPerson = new createPerson("Charlie", 40);
console.log(newPerson.name); // "Charlie"
console.log(newPerson.age); // 40