Loading
Build a Dynamic Avatar Component with React & TypeScript Tutorial (14 exercises)
Lesson

Discuss Types or Interfaces

Learn the difference between types vs. interfaces in TypeScript.

In React, we need to define the types of our component props.

There are two ways this can be done: interfaces or type aliases, or types for short.

Interfaces work really well for public APIs because they’re extensible. Supabase and CodeSandbox are two great examples that practice this.

Types cannot be changed after being created, so they’re more constrained and work well if this is inside your team’s codebase and not public-facing. Kent C. Dodd’s has a great example here.

The React TypeScript Cheatsheet has a useful table if you want to see a side-by-side comparison.

In general, I recommend using types unless your component is public-facing. Then use interfaces.

Resources

The following resources provide more information for this lesson:

Transcript

In React, we need to define the types for our component props. There are two ways this can be done; interfaces or type aliases, also called types for short, like these.

Interfaces work really well for public APIs because they're extensible. Interfaces can also be redeclared, and then they're later merged by the TypeScript compiler. Here, if I redefine that interface and add an alt property, now my props interface has both of those. This can be helpful for consumers of your public-facing API, who need to make changes to the types.

One example of this you can see in the codesandbox-client project. Inside of their SandboxEmbed, you can see that they use an interface to define the CodeSandboxerProps. It's even documented.

Types, on the other hand, are more constrained and cannot be redeclared or extended in the same way. This is usually safer for a private code base, because it means less mistakes and less gotchas for you and your team.

Here is an example of type in a blog post by Kent C. Dodds for a component that takes CalculatorProps. If you want to dig into the nuances between types versus interfaces, the React TypeScript Cheatsheet has this useful table, which compares them based on the different aspects that they each support.

In general, this is the rule that I follow. If your component is going to be a public-facing API, use interfaces. Otherwise, use types.