Search code examples
typescriptvariablesconstantsvarcode-formatting

Which way to creating variable in typescript better


I have a class:

export class ICar {
  wheels: number;
  color: string;
  type: string;
}

And when I want to create a variable Which way to creating will be better?

First:

const car = {
  wheels: 4,
  color: 'red',
  type: 'truck'
} as ICar;

Or second:

var car = new ICar(); 
car.wheels = 4; 
car.color = 'red'; 
car.type = 'truck'; 

Solution

  • If ICar is a class then the first example is most definitely wrong.

    Expanding on your example, let's say you have this:

    export class ICar {
        wheels: number;
        color: string;
        type: string;
    
        constructor() {
            this.wheels = 2;
            this.color = 'blue';
            this.type = 'motorcycle'
        }
    
        drive() {
            console.log('Driving!')
        }
    }
    

    The correct way to create an instance of a class is with the new keyword.

    // Good
    var car1 = new ICar(); 
    car1.wheels = 4; 
    car1.color = 'red'; 
    car1.type = 'truck'; 
    car1.drive() // Works
    

    Note that last line. car1.drive() only exists because the class was instantiated.

    If I do the same thing with a typecast:

    // Very bad
    const car2 = {
        wheels: 4,
        color: 'red',
        type: 'truck'
    } as ICar;
    car2.drive() // ! Runtime error !
    

    Now car2.drive() raises a runtime error because the method doesn't exist. This is because as ICar doesn't actually do anything in your compiled code. The as keyword decalres that the developer knows better than the typescript compiler and to treat a value as a different type than it otherwise would have. It does not actually transform that value into something else. So it does not change this object literal into an instance of ICar.

    So by using as here, you are actually creating a bug that typescript would have otherwise caught

    Playground with code.