Typescript: How to export a variable

TypescriptImportModuleExport

Typescript Problem Overview


I want to open 'file1.ts' and write:

export var arr = [1,2,3];

and open another file, let's say 'file2.ts' and access directly to 'arr' in file1.ts:

I do it by:

import {arr} from './file1';

However, when I want to access 'arr', I can't just write 'arr', but I have to write 'arr.arr'. The first one is for the module name. How do I access directly an exported variable name?

Typescript Solutions


Solution 1 - Typescript

There are two different types of export, named and default.

You can have multiple named exports per module but only one default export.

For a named export you can try something like:

// ./file1.ts
const arr = [1,2,3];
export { arr };

Then to import you could use the original statement:

// ./file2
import { arr } from "./file1";
console.log(arr.length);

This will get around the need for arr.arr you mentioned.

> How do pirates know that they are pirates? > They think, therefore they ARR!!

Solution 2 - Typescript

If you do:

var arr = [1,2,3];
export default arr;

...

import arr from './file1';

Then it should work

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCrazySynthaxView Question on Stackoverflow
Solution 1 - TypescriptKieranView Answer on Stackoverflow
Solution 2 - TypescriptMikael GidmarkView Answer on Stackoverflow