Borislav Hadzhiev
Thu Mar 10 2022·3 min read
Photo by Thought Catalog
Use named exports to export a function in TypeScript, e.g.
export function sum() {}
. The exported function can be imported by using a
named import as import {sum} from './another-file'
. You can use as many named
exports as necessary in a single file.
Here is an example of exporting a function from a file called another-file.ts
.
// 👇️ named export export function sum(a: number, b: number) { return a + b; } // 👇️ if using arrow function // export const sum = (a: number, b: number) => { // return a + b; // };
Note that using export
on the same line as the function's definition is the
same as exporting the function as an object after it has been declared.
function sum(a: number, b: number) { return a + b; } // 👇️ named export export { sum };
Here is how we would import the
function
in a file called index.ts
.
// 👇️ named import import { sum } from './another-file'; console.log(sum(13, 27)); // 👉️ 40
Make sure to correct the path that points to the another-file
module if you
have to. The example above assumes that another-file.ts
and index.ts
are
located in the same directory.
For example, if you were importing from one directory up, you would do
import {sum} from '../another-file'
.
TypeScript uses the concept of modules, in the same way that JavaScript does.
The example above uses a named export and a named import.
The main difference between named and default exports and imports is - you can have multiple named exports per file, but you can only have a single default export.
If you try to use multiple default exports in a single file, you would get an error.
export default function sum(a: number, b: number) { return a + b; } const example = 'hello world'; // ⛔️ Error: A module cannot have multiple default exports.ts(2528) export default example;
IMPORTANT: If you are exporting a variable (or an arrow function) as a default export, you have to declare it on 1 line and export it on the next. You can't declare and default export a variable on the same line.
Having said that, you can use 1
default export and as many named exports as
you need in a single file.
Let's look at an example that uses both - default and named exports.
const sum = (a: number, b: number) => { return a + b; }; // 👇️ default export export default sum; // 👇️ named export export const example = 'hello world';
And here is how you would import the two exports.
// 👇️ default and named import import sum, { example } from './another-file'; console.log(sum(13, 27)); // 👉️ 40 console.log(example); // 👉️ "hello world"
Notice that we didn't wrap the default import in curly braces.
We used a default import to import the sum
function and a named import to
import the example
variable.
Note that you can only have a single default export per file, but you can have as many named exports as necessary.
You also don't have to think about which members are exported with a default or named export.