Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript / JavaScript - import all types

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.

like image 246
Ondra Žižka Avatar asked Mar 29 '16 19:03

Ondra Žižka


People also ask

Can I import JavaScript in TypeScript?

The allowJs setting allows JavaScript files to be imported inside your TypeScript files. The setting basically allows JavaScript and TypeScript files to live in the same project.

Does TypeScript use Commonjs?

Yes, you can use it in a same manner that you would use it in Javascript. Typescript is superset of Javascript, all things possible in Javascript are also possible in Typescript.

Can you export a type in TypeScript?

Use a named export to export a type in TypeScript, e.g. export type Person = {} . The exported type can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file.


2 Answers

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.

like image 72
David Sherret Avatar answered Oct 09 '22 22:10

David Sherret


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
like image 33
user Avatar answered Oct 09 '22 23:10

user