Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we use typescript import * as?

Trying to developer a mental model for what import * as Blah does. For example:

import * as StackTrace from 'stacktrace-js';

How does that work and when do we do import *?

like image 249
Ole Avatar asked Mar 08 '19 02:03

Ole


People also ask

What does import * mean in JavaScript?

The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.

What does import type do in 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.

Can I use import in TypeScript?

With TypeScript 3.8, you can import a type using the import statement, or using import type .


2 Answers

Not really an answer, but a usage: Consider you have a few constant strings to be used in your application, you can define them in a single file and export

export const name = "NAME";
export const someOtherString = "SOME_CONST_STRING";

Then you can import them in a single variable using:

import * as CONST_STRINGS from './yourFilePath';

and use as

CONST_STRINGS.name 
CONST_STRINGS.someOtherString
like image 99
Sachin Gupta Avatar answered Sep 18 '22 14:09

Sachin Gupta


From the TypeScript doc:

Import the entire module into a single variable, and use it to access the module exports


The example code imports all exports of the stacktrace-js module into a variable called StackTrace.

Any named exports will be available as properties of the same name.

If the module has a default export it will be available as the default property.


Note also from the TypeScript Module doc:

Starting with ECMAScript 2015, JavaScript has a concept of modules. TypeScript shares this concept.

So TypeScript modules behave in the same way as ES6 JavaScript modules.


You would use import * as in either TypeScript or JavaScript when you want access to all of the module exports in a single variable.

like image 34
Brian Adams Avatar answered Sep 21 '22 14:09

Brian Adams