Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda