DEV Community

Fernanda Sayuri
Fernanda Sayuri

Posted on

TypeScript: Diferença entre type e interface

Se você usa React e TypeScript, provavelmente já se perguntou: qual a diferença entre type e interface? 🤔
Muitas vezes vejo que no dia a dia muitos devs escolhem usar um ou outro de forma arbitrária pois para a maioria dos casos acaba não tendo nenhum impacto real.

1. Uso

💡 Types são mais flexíveis, usado para definir um alias para um tipo.

type Person = {
  name: string;
  age: number;
};
Enter fullscreen mode Exit fullscreen mode

Além disso, type pode definir uniões de tipos, interface não.

type Status = "success" | "error" | "loading";
interface Status = "success" | "error" | "loading"; // ❌ Erro
Enter fullscreen mode Exit fullscreen mode

💡 Interfaces são ideais para definir a estrutura de objetos e podem ser estendidas com extends, facilitando a reutilização, utilizado para definir um contrato para um objeto.

interface User {
  name: string;
  age: number;
}
Enter fullscreen mode Exit fullscreen mode

2. Herança

Interface permite herança múltipla através de extends.

interface Employee extends Person {
  email: string;
}
Enter fullscreen mode Exit fullscreen mode

Type usa interseção (&) para combinar tipos.

type Employee = Person & {
  email: string;
};
Enter fullscreen mode Exit fullscreen mode

3. Qual Usar?

✔ Use interface quando estiver lidando com objetos e precisar de extensibilidade.
✔ Use type quando precisar de uniões de tipos, interseções, funções ou retorno de apis.

No geral, interfaces são preferidas para objetos, enquanto type é mais flexível para outras situações.

💖 Obrigado por ler, sinta-se à vontade para comentar e interagir!

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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs