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

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay