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

134
Visualizações
How to check type of object in typescript

I have a JSON file containing two different types of Objects in it. I want to iterate over the JSON with respect to their type. To illustrate my problem I created two different type of Object Animal and Person

Now I want to check the type of Object whether it is an Animal or Person.

type Animal = {
  name: string;
  legs: number;
}

type Person = {
  name: number;

}

const checkType = (isAnimalOrPerson: Animal | Person) =>{
  if(isAnimalOrPerson instanceof Animal){
     console.log("animal type");
  }
  else{

  }
}

Here I am getting an error on if the condition says: "Animal" only refers to a type, but is being used as a value here.

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

0

The "problem" with type is that it's a concept that only exists during development; once you transpile, it disappears, and TypeScript can't foresee the shape of a runtime value you might pass (unless you do assertion, i.e. explicit checks about what properties an object has). If you want to do type checking, you have to do it in another way, for example using classes, and then the approach would only work if you actually instantiate the class (as opposed to just using it as a shape):

class Animal {
    name: string;
    age: number;
    legs: number;
}

class Person {
    name: string;
    age: number;
    job: string;
    education: string;
}

let a: Animal = new Animal();
let b: Animal = { name: "Rex", legs: 4, age: 3 };
let c = new Person();

function checkType(arg: Animal | Person): string {
    if (arg instanceof Animal) {
        return "This is an animal";
    } else if (arg instanceof Person) {
        return "This is a person";
    }

    return "Can't tell";
}

console.log(checkType(a)); // This is an animal
console.log(checkType(b)); // Can't tell
console.log(checkType(c)); // This is a person
about 4 years ago · Juan Pablo Isaza Relatório

0

There's varoius ways to check PersonorAnimal value is also satisfies Animal.

  1. coerce by property
if ('legs' in toBeDetermined) {
  // toBeDetermined should be `Animal` in this block
}
  1. give Animal a unique symbol and check them
const animalTag: unique symbol = Symbol("Animal tag");

type Animal = {
  __brand__: typeof animalTag;
  name: string;
  legs: number;
}

if (toBeDetermined.__brand__ === animalTag) {
  // toBeDetermined can be coerced manually into Animal
}

I prefer 1 because Animal has disjoint property legs.

about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not sure will this help gonna help you

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

update i just found this look similar to your question https://medium.com/ovrsea/checking-the-type-of-an-object-in-typescript-the-type-guards-24d98d9119b0

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