If ICar
is defined as a class, then the initial example provided is indeed incorrect.
To elaborate on the example given, let's consider the following:
export class ICar {
wheels: number;
color: string;
type: string;
constructor() {
this.wheels = 2;
this.color = 'blue';
this.type = 'motorcycle'
}
drive() {
console.log('Driving!')
}
}
The proper way to create an instance of a class is by using the new
keyword.
// Correct approach
var car1 = new ICar();
car1.wheels = 4;
car1.color = 'red';
car1.type = 'truck';
car1.drive() // Executed successfully
It is important to note the significance of the last line car1.drive()
, which only works because the class was instantiated.
On the other hand, if we attempt a similar process with a typecast:
// Not recommended
const car2 = {
wheels: 4,
color: 'red',
type: 'truck'
} as ICar;
car2.drive() // Error at runtime
Subsequently, invoking car2.drive()
results in a runtime error since the method does not exist within that context. This issue arises because the use of as ICar
does not actually transform the object into an instance of ICar
; it solely informs Typescript to treat the value differently without altering its nature.
Hence, employing as
in such scenarios introduces bugs that could have been caught by Typescript.
Interactive playground with code snippet.