04-modules-namespaces.ts
Typescript/src/02-intermediate/04-modules-namespaces.ts
// ============================================
// 04. Modules and Namespaces
// ============================================
// ES6 Modules - Export
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
export const PI = 3.14159;
// Default export
export default function multiply(a: number, b: number): number {
return a * b;
}
// Import example (would be in another file):
// import multiply, { add, subtract, PI } from "./04-modules-namespaces";
// Type-Only Imports/Exports
export type User = {
name: string;
age: number;
};
export interface Product {
id: number;
name: string;
}
// Import example:
// import type { User, Product } from "./04-modules-namespaces";
// Namespaces
namespace MathUtils {
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
export const PI = 3.14159;
}
// Usage
console.log(MathUtils.add(5, 3));
console.log(MathUtils.PI);
// Nested Namespaces
namespace Geometry {
export namespace Circle {
export function area(radius: number): number {
return Math.PI * radius ** 2;
}
}
export namespace Rectangle {
export function area(width: number, height: number): number {
return width * height;
}
}
}
console.log(Geometry.Circle.area(5));
console.log(Geometry.Rectangle.area(4, 6));
// Merging Namespaces
namespace MyLib {
export function doSomething() {
console.log("Doing something");
}
}
namespace MyLib {
export function doSomethingElse() {
console.log("Doing something else");
}
}
// Both functions are available
MyLib.doSomething();
MyLib.doSomethingElse();
// Interface Merging
interface UserInterface {
name: string;
}
interface UserInterface {
age: number;
}
// Merged: { name: string; age: number; }
const user: UserInterface = {
name: "Alice",
age: 25
};
export { MathUtils, Geometry, MyLib };
相关文章
01-introduction.ts
01-introduction.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/01-introduction.ts).
阅读文章 →02-basic-types.ts
02-basic-types.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/02-basic-types.ts).
阅读文章 →03-variables.ts
03-variables.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/03-variables.ts).
阅读文章 →04-functions.ts
04-functions.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/04-functions.ts).
阅读文章 →05-interfaces.ts
05-interfaces.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/05-interfaces.ts).
阅读文章 →06-classes.ts
06-classes.ts — typescript source code from the Typescript learning materials (Typescript/src/01-beginner/06-classes.ts).
阅读文章 →