Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6/Typescript import: import * and names on a single line

How can I write this on 1 line?

import * as Express  from 'express';
import { Application, NextFunction, Request, Response } from 'express';

Your Dan the Dev

like image 342
Daniel Khoroshko Avatar asked Aug 24 '17 17:08

Daniel Khoroshko


People also ask

What is import * as in JS?

The import * as name syntax imports all exported content of a javascript file.

How do I write an import statement in TypeScript?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.

What is export {} in TypeScript?

TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

Should I use import type TypeScript?

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.


1 Answers

import and export have restricted syntax that allows to statically analyze them:

As listed in the documentation:

import defaultMember from "module-name";

import * as name from "module-name";

import { member } from "module-name";

import { member as alias } from "module-name";

import { member1 , member2 } from "module-name";

import { member1 , member2 as alias2 , [...] } from "module-name";

import defaultMember, { member [ , [...] ] } from "module-name";

import defaultMember, * as name from "module-name";

import "module-name";

As it can be seen, there's no import * as name, { member } from "module-name", so it isn't supported.

The reason why it isn't supported is because import * as name, { member } from "module-name" are interchangeable. It's either importing members one by one or as name namespace.

If both should be used for some reason, it should be:

import * as Express from 'express';
import { Application, NextFunction, Request, Response } from 'express';

Or if exports are real variables and not types/interfaces, it can be:

import * as Express from 'express';
const { Application, NextFunction, Request, Response } = Express;
like image 181
Estus Flask Avatar answered Oct 17 '22 16:10

Estus Flask