Typescript Cast Example

To start off, Typescript doesn’t have a cast in the way you’d expect coming from other languages:


class Car {
}

class BMW extends Car {
  fast() {
  }
}

let example: Car = new BMW();

((BMW)example).fast();

The way you do this correctly is quite neat:

if (example instanceof BMW) {
  example.fast();
}

The if statement auto-casts the variable you’re using (if you try to get too fancy with this, you’ll end up breaking the if statement into multiple nested statements).

If you use primitive types, you use “typeof” instead of “instanceof”, but otherwise it works the same:

if (typeof first === 'number') {          
  console.log(x + 1);
}        

Leave a Reply

Your email address will not be published. Required fields are marked *