DEV Community

Cover image for Type vs Interface in Typescript
Osinachi Chukwujama
Osinachi Chukwujama

Posted on

17 1

Type vs Interface in Typescript

Typescript offers two ways to define types. Either Type-Aliases or Interfaces. The choice of which to use depends on the complexity of the type you want to define.

For most cases, a Type-Alias would get the job done. Most things offered by interfaces are also available in the Type-Alias API. Let's see an example

Extending types

With interfaces, you could do this

interface Human {
  height: number,
  age: number,
  name: string
}

interface Woman extends Human {
  canConcieve: boolean
}
Enter fullscreen mode Exit fullscreen mode

Applying the same logic using Type-Aliases would be

type Human = {
  height: number,
  age: number,
  hairColor: string
}

type Woman = {
  canConcieve: boolean
}

const Chisom: Human & Woman = {
  height: 1.5,
  age: 20,
  hairColor: 'brown',
  canConcieve: true
} 
Enter fullscreen mode Exit fullscreen mode

People who prefer functional-style programming to Object-Oriented Programming may find Type-Aliases to be a better approach. Loosely defined types that can be combined.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (4)

Collapse
 
ucavalcante profile image
Ulisses Cavalcante

Nice approach.

Collapse
 
rconr007 profile image
rconr007

Thanks this seems very handy.

Collapse
 
aiosifelis profile image
Andreas Iosifelis

Very useful. Thanks!

Collapse
 
jwp profile image
JWP

Don't forget the Class. No explicit interface needed but acts just like an interface.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay