Home  Typescript   Import type ...

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)

Benefits of import type

  1. Performance: Reduces the amount of code that gets included in the final bundle since type information is stripped away during compilation.
  2. Clarity: Makes it clear which imports are only for type-checking, improving code readability.
  3. Avoids Circular Dependencies: Helps prevent circular dependencies by ensuring that only type information is imported.
Published on: Jun 25, 2024, 11:03 PM  
 

Comments

Add your comment