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

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

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 Denunciar

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