0
0
Typescriptprogramming~5 mins

Import syntax variations in Typescript

Choose your learning style9 modes available
Introduction

Import syntax lets you bring code from other files or libraries into your current file. This helps you reuse code and keep your project organized.

When you want to use a function or variable defined in another file.
When you need to include a whole library or module to use its features.
When you want to import only specific parts of a module to keep your code small.
When you want to rename an imported item to avoid name conflicts.
When you want to import everything from a module under one name.
Syntax
Typescript
import defaultExport from 'module-name';
import * as name from 'module-name';
import { export1, export2 } from 'module-name';
import { export1 as alias1 } from 'module-name';
import defaultExport, { export1, export2 } from 'module-name';
import 'module-name';

Use single quotes or double quotes for module names.

Default export means the main thing exported from a module.

Examples
Imports the default export from the 'react' module, usually the main React object.
Typescript
import React from 'react';
Imports everything from the local 'utils' file as an object named Utils.
Typescript
import * as Utils from './utils';
Imports only the useState and useEffect functions from the 'react' module.
Typescript
import { useState, useEffect } from 'react';
Imports useState but renames it to useLocalState to avoid name conflicts.
Typescript
import { useState as useLocalState } from 'react';
Sample Program

This program imports two functions, sqrt and pow, from the 'mathjs' library. It calculates the square root and the square of a number and prints the results.

Typescript
import { sqrt, pow } from 'mathjs';

const number = 16;
const root = sqrt(number);
const power = pow(number, 2);

console.log(`Square root of ${number} is ${root}`);
console.log(`${number} raised to power 2 is ${power}`);
OutputSuccess
Important Notes

Always check if the module you want to import from has a default export or named exports.

You can combine default and named imports in one statement.

Importing a module without bindings (import 'module-name';) runs the module code but does not import anything.

Summary

Import syntax helps you bring code from other files or libraries into your file.

You can import default exports, named exports, or everything as an object.

Renaming imports helps avoid name conflicts in your code.