9

In TypeScript, how do you "import *" from a file without creating any aliases?

E.g. I have a file "utils" with top-level exported functions and want to import all them without recreating the aliases for each function.

Something like this:

import * from "utils";

Is that possible?

3 Answers 3

4

You can't generate an automatic name, you have to give it a name that is local to your file. This is by design to give each file its own naming context.

// import the default export (something exported with "export default")
import Stuff from "./Stuff";

// import specific things only; aliases in this style are optional
import { ItemA as AliasA, ItemB as AliasB } from "./Stuff";
import { ItemA, ItemB } from "./Stuff";

// import everything at once, grouped under a common name
import * as Stuff from "./Stuff";

I ... want to import all them without recreating the aliases for each function.

It sounds like you'd want the third option from above.

but with this syntax creates an alias

I think the idea is that if you could just import everything while taking the names as they are defined, then you'd have naming collisions. The way this works, you're forced to choose a name for every import, leaving it up to the names you choose to avoid collisions rather than having the imports clobber each other.

I think you can do something similar, but only with .d.ts files. jquery.d.ts does it, but I'm not 100% solid on how it works. You can simply say:

// where the file is really Stuff.d.ts
import "./Stuff";
Sign up to request clarification or add additional context in comments.

Comments

0

I think the idea is to create a "Utils" module, attach all the functions and/or classes to it, put export in front of them, then export that instead, such as

module Utils {
    export function add(first:number, second:number):number {
        return first+second
    }
}
export = Utils

Though i haven't played around with the es6 module syntax in typescript yet, as it seems you're implying to use.

Comments

-1

You're close it's:

import * as utils from 'utils';

No curly braces.

2 Comments

but with this syntax creates an alias "utils", my original question was without creating aliases. For example, you have an external file with utility functions and you want to import them all in the global namespace and without repeating their names as in import { name } from "file".
Ah, ok. Nope, can't do that with the module syntax. You can extend the global namespace using some function like _.extend(global, utils); but then you would still need to declare the functions so TypeScript understands :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.