Explain the "import type" statement in TypeScript?
Last Updated :
09 May, 2024
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
Similar Reads
Explain the arrow function syntax in TypeScript Arrow functions in TypeScript are implemented similarly to JavaScript (ES6). The main addition in TypeScript is the inclusion of data types or return types in the function syntax, along with the types for the arguments passed into the function.What is arrow function syntax in TypeScript?Arrow functi
3 min read
TypeScript Interface vs Type Statements In TypeScript, interface and type are used to define the structure of objects and custom types. While interfaces enforce contracts for classes and support multiple inheritance, types offer flexibility for defining complex and reusable type aliases. Each serves distinct use cases.Table of ContentInte
3 min read
TypeScript Parameter Type Annotations TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript's static typing system, and they help catch ty
2 min read
How to import a module in Typescript ? Before starting with importing modules, first of all, we need to know the basics of modules in TypeScript. We know that JavaScript has come with the concept of modules from the ES6 version in 2015 and by 2020 had broad support in most web browsers and JavaScript runtimes. TypeScript also shares the
5 min read
TypeScript - Type Annotations and Type Inference TypeScript is a superset of JavaScript that adds static typing, helping developers catch errors early. Two core features are type annotations- where developers explicitly define variable, parameter, and return types, and type inference, where TypeScript automatically deduces types based on values or
5 min read