Home > Enterprise >  How can I use the types of a conditionally imported module in typescript?
How can I use the types of a conditionally imported module in typescript?

Time:10-22

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?

CodePudding user response:

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;
}

CodePudding user response:

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;
}
  • Related