Modules

TS Export Types

Exporting Types

TypeScript export types share interfaces across modules with export as.

Understanding TypeScript Export Types

In TypeScript, exporting types from a module allows you to share interfaces, types, and other declarations across different modules. This is essential for maintaining modular and organized code, especially in large projects. By using the export keyword, you can make certain types available for import in other modules, ensuring consistency and reuse.

Basic Export Example

To export a type or interface in TypeScript, you use the export keyword. This makes the type available to be imported in other files. Here's a simple example:

In the example above, we have defined a User interface with three properties. By using export, this interface can be imported and used in other modules.

Exporting Multiple Types

You can export multiple types from a single module. This is useful when you have several related types that need to be used together. Here's how you can do it:

In this example, two interfaces, Circle and Square, along with a union type Shape, are exported. This allows for flexible type usage in other parts of your application.

Using 'export as' for Alias

TypeScript allows you to export types under a different name using export as. This is particularly useful when you want to avoid naming conflicts or when you need to provide a more descriptive name:

Here, the Rectangle interface is exported as Rect. This alias can then be used when importing the type in other modules, providing flexibility in naming conventions.

Importing Exported Types

Once types are exported from a module, they can be imported into other modules using the import statement. Here's how you can import the User interface from the earlier example:

In this example, the User interface is imported from userTypes.ts. You can now use the User type to annotate variables and ensure they conform to the defined structure.

Conclusion

Exporting types in TypeScript is a powerful feature that promotes code reuse and modularity. By understanding how to export and import types, you can maintain clean and efficient code across your TypeScript projects. In the next post, we will explore Ambient Modules, which provide a way to describe the shape of modules when you don't have access to their source code.