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

189
Views
How can I use the types of a conditionally imported module in typescript?

I have an optional and platform-dependent dependency in my project, that I want to import conditionally like this:

import os from 'os';

export default async function doSomething(): Promise<foo | null> {
  if(os.type() === 'some os') {
    // "platform-dependent-module" exposes type "foo"
    const module = await import("platform-dependent-module");
    // do stuff
    return bar; // bar is of type foo
  }
  return null;
}

however this doesn't work, because the compiler Cannot find name 'foo'. Is it possible to expose the type definition without having to statically import the module?

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

0

Apparently, it's possible to import and exposed type separately. So one can statically import the type like so:

import type {foo} from 'module

and make use of the type, before dynamically loading the entire module. The final code would look something like this:

import os from 'os';
import type {foo} from 'platform-dependent-module';

export default async function doSomething(): Promise<foo | null | Error> {
  if(os.type() === 'some os') {
    try {
      // "platform-dependent-module" exposes type "foo"
      const module = await import('platform-dependent-module');
      // do stuff
      return bar; // bar is of type foo
    } catch (e) {
      return e;
    }
  }
  return null;
}
about 4 years ago · Juan Pablo Isaza Report

0

Yes, you can use TypeScript's Type Aliases.

And also make sure that the return type should be a promise in an async function.

And catch keyword should be replaced with else but there is no need of else.

import os from 'os';

type foo = any;

export default async function doSomething(): Promise<foo | null> {
  if(os.type() === 'some os') {
    // "platform-dependent-module" exposes type "foo"
    const module = await import("platform-dependent-module");
    // do stuff
    return bar; // bar is of type foo
  }
  return null;
}

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!