Default exports are a powerful feature in TypeScript that allow you to export a single value, function, or class as the main export of a module. They simplify module imports and provide a convenient way to organize your code.
In TypeScript, you can use the export default
keyword to specify a default export for a module. This feature is particularly useful when a module has a primary purpose or a main component that should be easily accessible.
To create a default export, simply add the export default
keywords before the value, function, or class you want to export:
// myModule.ts
export default function greet(name: string) {
return `Hello, ${name}!`;
}
When importing a default export, you can use any name you prefer without curly braces:
// main.ts
import sayHello from './myModule';
console.log(sayHello('Alice')); // Output: Hello, Alice!
While default exports are convenient, TypeScript also supports named exports. The choice between them depends on your module's structure and purpose:
Default Exports | Named Exports |
---|---|
One per module | Multiple per module |
Imported without curly braces | Imported with curly braces |
Can be renamed during import | Must use exact names (or aliases) |
Default exports are not limited to functions. You can also export classes:
// user.ts
export default class User {
constructor(public name: string, public age: number) {}
greet() {
return `Hello, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
// main.ts
import UserClass from './user';
const user = new UserClass('Bob', 30);
console.log(user.greet()); // Output: Hello, I'm Bob and I'm 30 years old.
While default exports offer simplicity, they can sometimes lead to naming inconsistencies across a large project. It's essential to balance the convenience of default exports with the clarity and predictability of named exports.
For more complex module structures, you might want to explore Export and Import patterns in TypeScript to effectively organize your code.
Default exports in TypeScript provide a straightforward way to export and import primary module functionality. By understanding when and how to use them, you can create more maintainable and intuitive module interfaces in your TypeScript projects.
To dive deeper into TypeScript modules, consider exploring Module Basics and Re-exports for more advanced module management techniques.