This is a demonstration taken from the MDN documentation showcasing the usage of the new
keyword
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
In TypeScript, the equivalent version of the function might look like:
/* Car type */
type CarDetails = {
make: string;
model: string;
year: number;
}
/* Setting "this" to be of type CarDetails */
function Car(this:CarDetails, make: string, model:string, year:number) {
this.make = make;
this.model = model;
this.year = year;
}
Although this approach provides IntelliSense/autocompletion while writing the code, it does not infer types when creating an instance using the new
keyword. Even after incorporating TypeScript into the method, instantiating an object like this:
const car1 = new Car('Eagle', 'Talon TSi', 1993);
still results in the type of car1
being any
How can I ensure that the type of car1
is inferred as the this
type of the Car
method?
(without explicitly specifying the type for the instance object, such as
const car1: CarDetails = new Car(...;
)