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

329
Views
Conditional return types in typescript

I'm trying to loop over an array of functions (doing network calls) that return different types of configuration objects. Based on this configuration I'm rendering react components with different props. But I'm struggling to get typescript to co-operate in this.

Here's a simplified example of what I had so far;

type FirstConfig = {
  a: 'a';
};

type SecondConfig = {
  b: 'b';
};

type ConfigObject = FirstConfig | SecondConfig;
type ConfigFunction = () => ConfigObject;
const configArray: ConfigFunction[] = [() => ({ a: 'a' }), () => ({ b: 'b' })];

configArray.map(getConfig => {
  const { a, b } = getConfig();
  console.log(a, b);
});

Whenever I loop over the array of config functions and call it, It seems to complain that none of the properties defined on the ConfigObject are present. Any tips/guidance here?

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is expected behavior. Your ConfigObject is either FirstConfig or SecondConfig. Before accessing their distinct properties you must resolve their type or if the property exists in that type.

There are different ways you can achieve this.

  1. Define a custom type guard for checking a type.

const isFirstConfig = (config: ConfigObject): config is FirstConfig => !!(config as any).a;

sandbox link

  1. Check if property exists in the object
const config = getConfig();
if ("a" in config) {
  // the config is of FirstConfig type here
}
  1. Add a common property for all config types by which you can verify it's type
type FirstConfig = {
  type: "first";
  a: "a";
};

type SecondConfig = {
  type: "second";
  b: "b";
};

then you can check types like this

const config = getConfig();
if (config.type === "first") {
  console.log("first type");
  // config is FirstConfig type in this 'if' block
}

sandbox

  1. Have a type for all configurations with properties set as optional
type ConfigObject = {
  a?: "a";
  b?: "b";
};

In this case you can write your initial code:

  const { a, b } = getConfig();

  console.log({ a, b });

sandbox

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!