import type in typescript
In TypeScript, import type
is used to import only the type definitions from a module, without including any runtime code. This can help improve performance and reduce bundle size by ensuring that only the type information is used and not the actual implementation code. It is especially useful in scenarios where you only need to refer to types for type-checking and do not need to use the actual code at runtime.
Example
Here's an example to illustrate the difference between import
and import type
:
Example Module (shapes.ts
)
// shapes.ts
export type Circle = {
radius: number;
};
export type Square = {
sideLength: number;
};
export function calculateArea(shape: Circle | Square): number {
if ('radius' in shape) {
return Math.PI * shape.radius ** 2;
} else {
return shape.sideLength ** 2;
}
}
Importing in Another Module (main.ts
)
-
Using
import
: When you useimport
, you import both the type definitions and the runtime code.// main.ts import { Circle, Square, calculateArea } from './shapes'; const circle: Circle = { radius: 5 }; const area = calculateArea(circle); console.log(`The area of the circle is ${area}`);
Here,
Circle
,Square
, andcalculateArea
are all imported, including the functioncalculateArea
. -
Using
import type
: When you useimport type
, you import only the type definitions and not the runtime code.// main.ts import type { Circle, Square } from './shapes'; import { calculateArea } from './shapes'; const circle: Circle = { radius: 5 }; const area = calculateArea(circle); console.log(`The area of the circle is ${area}`);
In this case,
Circle
andSquare
are imported only as types, which means they won't include any runtime code. The functioncalculateArea
is still imported as usual because it's a runtime value.
Benefits of import type
- Performance: Reduces the amount of code that gets included in the final bundle since type information is stripped away during compilation.
- Clarity: Makes it clear which imports are only for type-checking, improving code readability.
- Avoids Circular Dependencies: Helps prevent circular dependencies by ensuring that only type information is imported.