type 和 interface 的区别
type
可以定义基本类型 也可以定义对象、数组、函数等
// 1. 定义基本类型
type StudentNameType = string;
const studentName: StudentNameType = "张三";// 2.定义对象
type StudentType = { name: string;age: number;
}
const student: StudentType = {name: "张三",age: 18
}// 3. 定义数组
type Love = string[];
const love: Love = ["足球", "篮球"];// 4. 定义函数
type Add = (a: number, b: number) => number;
const add: Add = (x,y)=>x+y;
相比之下,interface
则不能定义基本类型。这是从定义类型这个基本功能上边!
初次之外还有其他不同,
- type 可以定义联合类型、交叉类型,而 interface 则是被继承和实现。
- type 不可以重复定义,而 interface 允许重复定义 并会被合并。
namespace 和 module 的区别
namespace 和 module 都可以用来组织代码,在编译之后代码是一样的,生成一个全局对象。
// 源码(namespace 可以 替换为 module)
namespace JSQUtilsNamespace { const name = "计算器工具";type Add = (a: number, b: number) => number;const add: Add = (x,y)=>x+y;console.log(add(1,2));
}
// 编译后
var JSQUtilsNamespace;
(function (JSQUtilsNamespace) {var name = "计算器工具";var add = function (x, y) { return x + y; };console.log(add(1, 2));
})(JSQUtilsNamespace || (JSQUtilsNamespace = {}));
虽然编译后的代码是一样的,但是两者的设计理念不同。
- namespace:主要用于组织和封装代码,在同一个文件中将相关的代码分组。它是一种 内部模块化,并没有跨文件的依赖管理和导入导出功能。
- module:module 用于 外部模块化,在多个不同文件之间共享代码。
// utils.ts
namespace Utils {export function add(x: number, y: number): number {return x + y;}export const name = "UtilsModule";
}const sum = Utils.add(1, 2); // 使用 namespace 中的功能
console.log(sum); // 输出 3
// utils.ts
module Utils {export function add(x: number, y: number): number {return x + y;}export const name = "UtilsModule";
}// app.ts
/// <reference path="utils.ts" />
const sum = Utils.add(1, 2); // 引用 utils.ts 中的 module
console.log(sum); // 输出 3
TypeScript 1.5 之后的变化
从 v1.5 开始,module 关键字被 废弃,并由 ES6 的 import/export 模块语法取代。现在的模块系统更符合现代 JavaScript 模块化标准。namespace 仍然作为TS组织代码的工具存在,但它不再是标准的模块系统。
不过 ts 还是保留了 declare module xxx
的这种特殊用法,主要用于 为外部模块或库声明类型。这种用法通常出现在 d.ts 文件 中,目的是 为 JavaScript 库或没有类型定义的第三方模块提供类型声明。这样 TypeScript 就能理解这些模块的接口,以便在项目中使用时提供类型检查。