NB

Husband, Father, and Solver of Problems.

Dangerous "As" – Typescript

Thu Dec 17 2020

TL;DR

Do This:

const car: Car = someObj

Not This:

const car: Car = someObj as Car

Or This:

const car: Car = <Car>someObj

I'm still pretty new to Typescript,

and until today I thought that I should type my objects this way:

const car = {
  color: "RED",
  drivetrain: "AWD",
} as Car

interface Car {
  color: string
  drivetrain: "AWD" | "2WD" | "4WD"
}

It wasn't until I was seeing undefined property errors that I decided to take a look at what the "as" keyword is actually doing here. Up until this point, I thought that what I was doing was typing const car to the interface Car. What the as keyword actually does, is forces whatever object I'm defining into that type.

What makes this dangerous, is that when you typecast an object like this, the compiler will not warn you of missing properties and will give you a false sense of security because you're not seeing compilation errors. For example, this will still compile even though we didn't include a color property:

const car = {
  drivetrain: "AWD",
} as Car

interface Car {
  color: string
  drivetrain: "AWD" | "2WD" | "4WD"
}

With this in mind here's the code above written in a type-safe way:

const car: Car = {
  color: "RED",
  drivetrain: "AWD",
}

interface Car {
  color: string
  drivetrain: "AWD" | "2WD" | "4WD"
}