Home > Web Front-end > JS Tutorial > TypeScript: Difference between Type and Interface

TypeScript: Difference between Type and Interface

Linda Hamilton
Release: 2025-01-30 12:31:10
Original
566 people have browsed it

TypeScript: Diferença entre type e interface

Using React and TypeScript, the doubt about the difference between type and interface is common. In practice, many developers use them interchangeably, as in many scenarios the impact is minimal. Let's clarify the nuances:

1. Use:

type offers greater flexibility, acting as a type for types.

<code class="language-typescript">type Pessoa = {
  nome: string;
  idade: number;
};</code>
Copy after login

A crucial advantage: type allows type unions, something that does not allow. interface

<code class="language-typescript">type Status = "sucesso" | "erro" | "carregando";
interface Status = "sucesso" | "erro" | "carregando"; // ❌ Erro</code>
Copy after login

, in turn, it is ideal for defining the structure of objects and supports inheritance through interface, promoting code reuse. Defines a contract for an object. extends

<code class="language-typescript">interface Usuario {
  nome: string;
  idade: number;
}</code>
Copy after login

2. Inheritance:

Allows multiple inheritance with interface. extends

<code class="language-typescript">interface Funcionario extends Pessoa {
  email: string;
}</code>
Copy after login

Uses intersection (type) to combine types. &

<code class="language-typescript">type Funcionario = Pessoa & {
  email: string;
};</code>
Copy after login

3. Which use?

    Use
  • When working with objects and need extensibility. interface
  • Use
  • When you need types of type, intersections, functions or types of return of APIs. type
In short,

is usually preferable to objects, while interface offers greater flexibility for other situations. type

Thanks for your reading! Comments and interactions are welcome!

The above is the detailed content of TypeScript: Difference between Type and Interface. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template