Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

283
Visualizações
TypeScript why use traditional classes instead of interfaces?

I can do this:

enum DogsKinds {
  Labrador,
  Aski
}

class Dog {
  name: string;
  kind: DogKinds;
  constructor() {}
}

And then init a dog object:

const dog = new Dog();

However I can do the same with interface:

interface Dog {
  name: string;
  kind: DogsKind;
}

const dog: Dog = {
  name: 'some name',
  kind: DogsKinds.Labrador
}

And get the same result - easier.

What are the differences, when to use interface and when to use classes, is there a best practice or rule of thumb?

It seems that interfaces are easier to work with, if I wrong please correct me.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think one important difference is finding out at runtime which kind of object you are dealing with when using inheritance.

With classes you can use the instanceof operator:

if (animal instanceof Dog) { /* ... */ }

When you are just using plain objects with TypeScript you will have to supply an additional property to differentiate the types during runtime.

type AnimalType = 'dog' | 'cat'

interface Dog extends Animal {
  type: 'dog'
  name: string;
  kind: DogsKind;
}

if (animal.type === 'dog') { /* ... */ }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda