Home > front end >  How to use a module in typescript (array syntax)?
How to use a module in typescript (array syntax)?

Time:04-02

import http from "http";
import https from "https";

const module = (options.port === 443 ? "https" : "http");

const req = [module].request(options, (res) => {
  console.log(res.statusCode);
});

error TS2339: Property 'request' does not exist on type 'string[]'.

CodePudding user response:

The [module] array syntax should be changed to module.

Additionally, you should use conditional importing to only import the module that you require. Please note that because import returns a promise, you will need to add the code in your example into an async function and prepend await in front of each import statement:

async function invokeHttpRequest() {
  const module = (options.port === 443 ? await import("https") : await import("http"));

  const req = module.request(options, (res) => {
    console.log(res.statusCode);
  });
}

CodePudding user response:

Something like this?

import http from "HTTP";
import https from "https";

const module = (options.port === 443 ? https : http);

const req = module.request(options, (res) => {
   console.log(res.statusCode);
});
  • Related