0
0
Typescriptprogramming~5 mins

Type-only imports and exports in Typescript

Choose your learning style9 modes available
Introduction

Type-only imports and exports let you use types without adding extra code when your program runs. This keeps your code clean and fast.

When you want to use a type from another file but don't need the actual code.
When you want to avoid increasing the size of your final program by importing only types.
When you want to clearly separate types from real code in your imports and exports.
When you want to prevent accidental runtime imports that are only meant for type checking.
Syntax
Typescript
import type { TypeName } from './file';

export type { TypeName };

Use import type to import only types, not code.

Use export type to export only types from a file.

Examples
This imports only the User type from another file. No code is imported.
Typescript
import type { User } from './userTypes';
This exports the User type so other files can use it.
Typescript
export type { User };
Here, Config is imported only as a type to check the function parameter.
Typescript
import type { Config } from './config';

function setup(config: Config) {
  // use config type here
}
Sample Program

This program imports only the User type from userTypes.ts. It uses the type to check the parameter of the greet function. The program prints a greeting message.

Typescript
/* userTypes.ts */
export type User = {
  name: string;
  age: number;
};

/* main.ts */
import type { User } from './userTypes';

function greet(user: User) {
  console.log(`Hello, ${user.name}!`);
}

const person = { name: 'Alice', age: 30 };
greet(person);
OutputSuccess
Important Notes

Type-only imports do not add any code to the final JavaScript output.

They help keep your code smaller and faster by avoiding unnecessary imports.

If you try to use a type-only import as a value, TypeScript will give an error.

Summary

Type-only imports and exports let you use types without importing code.

Use import type and export type to keep your code clean.

This helps your program run faster and stay smaller.