TypeScript / JavaScript - import all types

2020-05-29 13:07发布

问题:

How can I import all types from certain file?

Let's say I have myClass.ts and otherClass.ts. I want to import all classes from otherClass.ts.

I've seen few syntaxes for imports.

import ClassA, { ClassB, ClassC } from 'otherClass';

import * as foo from 'otherClass';

import foo = require('otherClass');

import 'rxjs/Rx';
  1. The first needs me to list everything. I'd like to import all types.

  2. The second syntax needs the namespace prefix: foo.ClassA.

  3. I understand that the last one is TypeScript 1.4, but still supported.

Is there something like the following?

import * from "otherClass";
...
   var x = new ClassA()

Also, what's the meaning of the { ... } and some of the types being outside and some inside?

The documentation doesn't hint anything such.

回答1:

With ES6 modules, the closest thing available to what you want is a namespace import:

import * as foo from './otherClass';

The use it individual exports as

foo.ClassA

You can see the available kinds of imports in the import documentation.

Also, what's the meaning of the { ... } and some of the types being outside and some inside?

That's for importing named exports. You can read about that in the documentation I referenced or in my answer here.



回答2:

You can use triple slashes import:

/// <reference path="./actionsCollection.ts" />

They must have to be the on the first line(s) of the file.

  1. When do I need a triple slash reference?
  2. https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html