全局声明的(类型,函数、类等)可直接使用
interface和type的全局声明,declare可以省略,例如:
// 声明一个全局类型 declare/type 可以省略
declare interface IAnimal {
name: string;
age?: number;
}
// 声明string别名
type str = string;
// 声明一个全局函数
declare function add(x: number, y: number): number;
模块声明的有两种方式:1,字符串 2,模块名
字符串方式:
// 字符串方式,需要import才能使用(CJS写法)
// import {AnimalI} from 'global_type'
declare module 'global_type' {
export type AnimalI = {
name: string;
};
}
// 模块通配符,任何.type结尾的模块, 都将拥有IDog这个类型
declare module '*.type' {
// module中的必须导出才行
export type IDog = {
name: string;
};
}
模块名方式:
// 模块名方式, 可直接使用(ESM写法,类似namespace)
declare module global_type_1 {
export type AnimalII = {
name: string;
};
}
模块可以导出(需要import):
// 模块导出(ESM独有的)
export module global_type_3 {
export type Animal_III = {
name: string;
};
}
// 模块导出形式, 使用时需要import
import { global_type_3 } from '../types/exmodule';
let catIII: global_type_3.Animal_III = {
name: 'catIII',
};
console.log(catIII);
模块别名
declare module global_type_1 {
export type AnimalII = {
name: string;
};
}
// 模块别名
import IAni = global_type_1.AnimalII;
let iAni: IAni = {
name: 'iAni',
};
console.log(iAni);
namespace声明 , 类似module
把代码中的module关键字换成namespace即可
declare namespace global_type_2 {
export type AnimalIII = {
name: string;
};
}
global关键字, 和module,namespace差不多
全局变量和类型就不需要使用declare声明,可以直接写在declare global代码块中
declare global 中需要用import或者export 使声明文件成为一个模块,表明这个文件是有导出的
import '';
declare global {
type IDog1 = {
name: string;
};
let animal1: IDog1;
}
// 或者
// export {};
// 直接使用
let IDog11: iDog1 = {
name: 'IDog11',
};
console.log(IDog11);
命名空间 OR 模块?
模块可以利用模块加载器(如CommonJS/Require.js)或支持ES模块的运行时来管理依赖和导入导出。模块是ES6标准的一部分,是现代代码的推荐组织方式。适用于需要动态加载、封装和复用代码的场景
命名空间可以避免全局变量的命名冲突,但也会增加组件依赖的难度,适用于需要在全局范围内定义变量、函数、类、接口等的场景