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

145
Visualizações
Function returning an object type if the object is an instance of x?

I need a TypeScript function to test if an object is of a specific type. If so, the method should return this type. If not the method should return undefined. I want to use this function in the following way:

const mySpecialObject = isSpecialObject(source);
if (mySpecialObject) {
  console.log(mySpecialObject.getSpecialProperty());
}

I tried to export a function like this one:

export function isSpecialObject(element: SomeBaseObject): SpecialObject  {
    if (element instanceof SpecialObject) {
        return element;
    }
    return undefined;
}

But the compiler claimed that 'undefined' is not assignable of Type SpecialObject

How should a TypeScript function with this behavior look?

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

0

You want a type predicate function to make this thing safer!

export function isSpecialObject(element: SomeBaseObject): element is SpecialObject  {
    return element instanceof SpecialObject;
}

if (isSpecialObject(element)) {
   // element is safe to use as SpecialObject
}

It's also possible to use a type predicate function for multiple types like this:

export function isSpecialObject(element: SomeBaseObject): element is SpecialObject | SpecialObjectSub1 | SpecialObjectSub2 {
    return element instanceof SpecialObject || element instanceof SpecialObjectSub1 || element instanceof SpecialObjectSub2;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Since the two possible outcome to be returned by the function are SpecialObject or undefined, so undefined can be added as a possible returned type. as below

export function isSpecialObject(element: SomeBaseObject): SpecialObject | undefined  {
  if (element instanceof SpecialObject) {
    return element;
  }
  return undefined;
}
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