Explain the “import type” statement in TypeScript?

In TypeScript 3.8.3, import type statements were introduced to allow the import of type information only from a module. This implies that within your current codebase, you can make use of another module’s types for annotation and declaration purposes without importing values from the module during runtime.

Key Benefits

  • Improved Type Safety: By expressing interest in types alone, you encourage better type checking which eliminates some runtime errors.
  • Reduced Bundle Size: Considering that compiled JavaScripts do not include genuine values obtained through modules, it is possible to cut down on bundle size significantly especially when you are working with bulky modules.
  • Clearer Code Intent: With import type, code becomes more self-explanatory because it shows that only types matter as far as checking them is concerned.

Syntax:

 // Import specific type(s)
import type { TypeName } from "module-path";

// Import all types from a module import type * as ModuleName from "module-path";

Specific Type Import: Import individual types using curly braces around the names, separated by commas.

All Types Import: Use * as ModuleName to import all exported types from a module.

When to Use import type

  • Type Annotations: When you are providing type information for variables, function arguments, return values or properties.
  • Type Aliases: When creating type aliases that reference types from other modules.
  • Interface Extensions: When extending interfaces defined in external modules.
  • Generic Constraints: When specifying type constraints for generics that involve types from other modules.

Important Considerations

  • No Runtime Value Import: The imported types do not exist at runtime. You cannot use them to create instances of classes, call functions or access properties that have runtime behavior.
  • Conditional Imports: import type statements cannot be used in conditional statements like if or switch.

Example 1: To demonstrate using the “import type” statment in Typescript in the NodeJs environment.

JavaScript
//user.ts

export interface User {
  name: string;
  age: number;
}
JavaScript
// app.ts
import type { User } from "./user"; 
// Import type information only

function createUser(userData: User) {
  // Type checking ensures `userData` 
  // has the expected properties
  console.log(`Name: ${userData.name}, Age: ${userData.age}`);
}

const user1: User = { name: "Pankaj", age: 20 };
createUser(user1);

Run the Node.js script:

tsc app.ts  # Compile to JavaScript (app.js)
node app.js  # Run the compiled JavaScript

Output:

Name: Pankaj, Age: 20

Example 2: To demonstrate using the import type statement in the the browser environment.

HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>TypeScript Example</title>
    <script src=
"https://unpkg.com/typescript@latest/lib/lib.dom.d.ts">
      </script>
</head>

<body>
    <h1>Output from TypeScript</h1>
    <script>
        // Reference compiled JavaScript files
        const user = new Function('return import("./user.js")')();
        // Dynamic import for browser
        const app = new Function('return import("./app.js")')();
        // Dynamic import for browser
        // Use imported module (types only)
        app
            .createUser({ name: "Pankaj", age: 20 });
    </script>
</body>

</html>
JavaScript
//user.ts
export interface User {
  name: string;
  age: number;
}
JavaScript
//app.ts
import type { User } from "./user"; // Import type information only

function createUser(userData: User) {
  console.log(`Name: ${userData.name}, Age: ${userData.age}`);
}

const user1: User = { name: "Pankaj", age: 20 };
createUser(user1);

Run the HTML file:

Open index.html in web browser to see the output:

Name: Pankaj, Age: 20


Contact Us