Answer the question
In order to leave comments, you need to log in
Why does Typescript let you create an object without specifying required fields?
Good afternoon!
I created a class, after which I created an instance of an object from this class through the constructor. The object was successfully created and output to the console, the file was compiled into .js, BUT: why didn't I get an error that "Type '{}' is missing the following properties from type 'Vehicle': isSpecial, brand, model, and 2 more. " ? Indeed, in the class description, these fields are not optional, but nevertheless, I was able to create an object without specifying them, there was no error. But when I create an object like this: "const toyota: Vehicle = {}", there is an error. Through the constructor - no. Why?
class Vehicle {
isSpecial: boolean;
wheels: number;
brand: string;
model: string;
mileage: number;
isUsed: boolean;
constructor (wheels: number, mileage: number) {
this.wheels = wheels;
this.mileage = mileage;
}
drive(): void {
this.mileage += 100;
};
}
const toyota: Vehicle = new Vehicle(4, 200);
console.log(toyota);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question