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>
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>
, 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>
2. Inheritance:
Allows multiple inheritance with interface
. extends
<code class="language-typescript">interface Funcionario extends Pessoa { email: string; }</code>
Uses intersection (type
) to combine types. &
<code class="language-typescript">type Funcionario = Pessoa & { email: string; };</code>
3. Which use?
interface
type
is usually preferable to objects, while interface
offers greater flexibility for other situations. type
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!