Peter
Peter

Reputation: 289

Importing module and avoid prepending the name

I use TypeScript together with CommonJS module loader.

I have one file called Util.ts and another called Main.ts

I export a class in the Util.ts file

 export class Set {

 }

And I import it in my Main.ts

import * as Util from "./Util";

But in my main file I have to write new Util.Set() in order to access the Set class. Is there a way such that I can avoid prepending the Util identifier? It would be nice if I could write new Set().

Upvotes: 1

Views: 43

Answers (2)

Fenton
Fenton

Reputation: 251212

In addition to Nathan's excellent answer, which I won't repeat here... you can set an alias for one aspect of the import, if you need to give something a different name:

import * as Example from './module1'

// Long hand
var person = new Example.Person('Steve');

// Create an alias (doesn't have to be "Person")
import Person = Example.Person;

// Short hand
var person2 = new Person('Peter');

Upvotes: 1

Nathan Friend
Nathan Friend

Reputation: 12834

You can import the class directly like this:

import {Set} from './Util';

If you have more than one value to import from Util, you can do this:

import {Set, MyOtherClass} from './Util';

Upvotes: 2

Related Questions