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.
type Pessoa = { nome: string; idade: number; };
A crucial advantage: type
allows type unions, something that does not allow. interface
type Status = "sucesso" | "erro" | "carregando"; interface Status = "sucesso" | "erro" | "carregando"; // ❌ Erro
, 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
interface Usuario { nome: string; idade: number; }
2. Inheritance:
Allows multiple inheritance with interface
. extends
interface Funcionario extends Pessoa { email: string; }
Uses intersection (type
) to combine types. &
type Funcionario = Pessoa & { email: string; };
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!