Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda