DEV Community

Manav Misra
Manav Misra

Posted on

Why is the Keyword `as` Needed When Narrowing TypeScript Interfaces With an `if`?

Given some interfaces for Circle and Square as follows:

export default interface Circle {
  radius: number
}
export default interface Square {
  sideLength: number;
}

I can use as to calculate the area properly:

function getArea(shape: Circle | Square) {
  if ((shape as Circle).radius) {
    return Math.PI * (shape as

Discussion (0)