-- Ví dụ Mở rộng namespace trong typescript 2 file khác nhau và những chú ý (ok)
🔹 Tổ chức file
lessCopyEditproject/
│── file1.ts // Khai báo namespace lần 1
│── file2.ts // Mở rộng namespace
│── main.ts // Sử dụng namespace
│── tsconfig.json // (nếu cần)1️⃣ Khai báo namespace trong các file
file1.ts
file1.tstypescriptCopyEditexport namespace MyNamespace {
export const name = "TypeScript";
}file2.ts
file2.tstypescriptCopyEditimport { MyNamespace } from "./file1"; // Import namespace từ file1.ts
export namespace MyNamespace {
export const version = "5.0";
export function getInfo() {
return `${MyNamespace.name} - Version ${version}`;
}
}2️⃣ Sử dụng namespace trong file thứ ba
main.ts
main.ts3️⃣ Chạy bằng ts-node
ts-node🔹 Cấu hình tsconfig.json (Tùy chọn)
tsconfig.json (Tùy chọn)✅ Tóm tắt
🔹Lỗi Individual declarations in merged declaration 'MyNamespace' must be all exported or all local.
🔥 Cách khắc phục lỗi
✅ Cách 1: Đảm bảo tất cả namespace đều được export
export🔹 Tệp file1.ts
file1.ts🔹 Tệp file2.ts
file2.ts🔹 Tệp main.ts
main.ts🔹 Chạy với ts-node
ts-node✅ Cách 2: Dùng /// <reference path="..." /> nếu không muốn dùng import/export
/// <reference path="..." /> nếu không muốn dùng import/export🔹 Tệp file1.ts
file1.ts🔹 Tệp file2.ts
file2.ts🔹 Tệp main.ts
main.ts🔹 Chạy với ts-node
ts-node🚀 Kết luận
🏗 Cấu trúc tệp
✅ Cách 1: Dùng export namespace và import (Chạy được với ts-node)
export namespace và import (Chạy được với ts-node)📌 Tệp file1.ts - Khai báo namespace ban đầu
file1.ts - Khai báo namespace ban đầu📌 Tệp file2.ts - Mở rộng namespace
file2.ts - Mở rộng namespace📌 Tệp main.ts - Sử dụng namespace
main.ts - Sử dụng namespace🚀 Chạy với ts-node
ts-node🔥 Lợi ích của cách này
✅ Cách 2: Dùng /// <reference path="..." /> (Dành cho biên dịch bằng tsc)
/// <reference path="..." /> (Dành cho biên dịch bằng tsc)📌 Tệp file1.ts - Khai báo namespace ban đầu
file1.ts - Khai báo namespace ban đầu📌 Tệp file2.ts - Mở rộng namespace
file2.ts - Mở rộng namespace📌 Tệp main.ts - Sử dụng namespace
main.ts - Sử dụng namespace🚀 Chạy với tsc
tsc🎯 So sánh hai cách
Previous-- Cấu hình tsconfig.json để không sử dụng reference nữa (ok)NextMở rộng hoặc ghi đè interface đã khai báo trong file index.d.ts với thuộc tính initialData (ok)
Last updated