文章目录
namespace 命名空间
【命名空间嵌套】
【命名空间合并】
【命名空间别名】
module
【通配符模块声明】
namespace 主要用于解决命名冲突,他会在全局生成一个对象,在 namepace 内部的成员都要通过这个对象访问。使用命名空间可以解决代码和第三方库之间的同名冲突。
若命名空间使用 declare 关键字,则命名空间内部属性不需要再使用 declare 。
如果需要在命名空间外部使用内部成员,则需要添加 export 关键字前缀。
命名空间内部成员的访问使用点号 . 来实现。
// 定义命名空间
namespace Utils {
export namespace Message {
const name = 'jack'
export function getName() {
console.log(name)
}
export interface Validation {
age: number
}
}
}
// 在命名空间外使用成员
Utils.Message.getName(); // jack
console.log(Utils.Message.str); // --报错
命名空间支持嵌套,即可以将命名空间定义在另外一个命名空间里头。
namespace Utils {
// 命名空间嵌套
export namespace Messaging {
export function log(msg:string) {
console.log(msg);
}
}
}
Utils.Messaging.log('hello') // "hello"
多个同名的 namespace 会自动合并
namespace Animals {
export class Cat {}
}
namespace Animals {
export interface Legged {
numberOfLegs: number;
}
export class Dog {}
}
// 等同于
namespace Animals {
export interface Legged {
numberOfLegs: number;
}
export class Cat {}
export class Dog {}
}
命名空间中的非 export 的成员不会被合并,但是它们只能在各自的命名空间中使用。
namespace N {
const a = 0;
export function foo() {
console.log(a); // 正确
}
}
namespace N {
export function bar() {
foo(); // 正确
console.log(a); // 报错
}
}
命名空间别名是使用 import 关键字定义的。
namespace Utils {
// 命名空间嵌套
export namespace Messaging {
export function log(msg: string) {
console.log(msg);
}
}
}
import Um = Utils.Messaging;
Um.log('haha'); // haha
Utils.Messaging.log('hello'); // hello
TS 支持 CommonJS 和 ESM 两种模块系统,使得声明模块有两种写法,分别是使用字符串和变量名 。
CommonJS 的写法遵循匹配文件的相对或绝对路径,通常模块名作为字符串字面量,该方法不支持导出模块,只允许使用 declare 定义全局模块,并且使用时需要使用 import 导入。
// global.d.ts
declare module "global_type" {
export type IAnimal = {
name: string
}
}
// src/index.ts
import * as global_type from "global_type"
const myObject: global_type.IAnimal = {}
ESM 的写法和定义变量一样,使用变量名匹配标识符进行模块的导入,这种方式与定义命名空间(namespace)的效果一样,使用 ESM 定义的全局模块可以直接使用,不需要导入。
// global.d.ts
declare module global_type {
export type IAnimal = {
name?: string
}
}
// src/index.ts
const myObject: global_type.IAnimal = {}
在 react 内置类型声明文件中可以看到看到下面代码,这种写法是 CommonJS 模块系统独有的。
// react-app.d.ts
declare module '*.png' {
const src: string;
export default src;
}
// App.tsx
import logo from './logo.png';
这段代码中使用了 *.png 通配符,声明了一个全局模块,匹配所有 .png 结尾的模块,导入的 .png 类型文件就会声明为 string 类型。
参考:https://blog.csdn.net/time_____/article/details/129443454
TypeScript 教程——阮一峰·著
TypeScript 中文网
TypeScript 官网