Typescript export
Created By: chatGPT
TypeScript is a superset of JavaScript that adds static types. To use TypeScript effectively, you might often need to export various functionalities like functions, classes, or variables from one module so they can be used in another. You can do this using the
export
keyword.// Exporting a constant
export const PI = 3.14;
// Exporting a function
export function add(x: number, y: number): number {
return x + y;
}
// Exporting a class
export class Circle {
constructor(public radius: number) {}
area(): number {
return PI * this.radius * this.radius;
}
}
You can also export multiple items at once. This can be done either in one statement or by mixing it with individual exports throughout the file.
// Exporting multiple items at once
const E = 2.718;
export { E, add, Circle };
If you want to export something without specifying its name upon import, you can use the
default
keyword. This is useful when you want to export a single value or function as the primary export of the module.// Default export of a function
export default function multiply(x: number, y: number): number {
return x * y;
}
When importing, you can use the following syntax to get your exports. Notice how importing a default export is different from importing named exports.
By properly organizing your exports and imports, you can create a clean and efficient codebase. This helps maintain readability and allows for better collaboration in larger projects.// Importing named exports
import { PI, add, Circle } from './math';
// Importing the default export
import multiply from './math';