Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!