跳到主要内容

TypeScript全局类型定义的方式

· 阅读需 7 分钟
Oxygen

TypeScript 全局类型定义或者覆盖在日常开发中经常使用,下面介绍几种常见的方式。

使用declare global命名空间

在包含在 TypeScript 类型检测文件目录内的任意位置新建xxx.d.ts文件,并使用declare global全局命名空间语法来定义覆盖类型,例如:

declare global {
/*~
*~ 定义 String 类型实例上的方法
*/
interface String {
fancyFormat(): string;
}
}

/* 文件内必须包含一个 export 语句 */
export {};

也可以使用declare global定义一些全局变量,全局类型,全局方法等:

declare global {
let timeout: number;
const version: string;

function checkCat(c: Cat, s?: VetID);

class Cat {
constructor(n: number);
readonly age: number;
purr(): void;
}

interface CatSettings {
weight: number;
name: string;
tailLength?: number;
}

/*~
*~ 定义 Window 实例上的属性或者方法
*/
interface Window {
a: string;

myFn: VoidFunction;
}
}

export {}
危险

使用declare global定义全局类型时,该文件内部必须包含至少一个export语句!

使用declare module命名空间

如果要对一个第三方的包覆盖其类型定义,可以使用import <module>declare module语法,例如覆盖axios的类型定义。

axios在其实例方法上定义的类型存在一个无用的泛型参数,这个参数在使用getpost等方法时必须要传,给开发带来了一些不便;同时项目自身可能会对axios进行封装,添加一些额外的config参数,因此我们可以在项目中通过以下方式来全局覆盖axios自身的类型定义:

/*  */
import axios from 'axios';

/**
* 覆盖 AxiosRequestConfig
*/
declare module 'axios' {
/**
* 自定义配置参数
*/
export interface AxiosRequestConfig {
/**
* 即时更新
*/
useTimeStamp?: boolean;
}

// https://github.com/axios/axios/issues/1510#issuecomment-525382535
export interface AxiosInstance {
request<T = any> (config: AxiosRequestConfig): Promise<T>;
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
head<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
}
}

使用全局模块类型声明

在包含在 TypeScript 类型检测文件目录内的任意位置新建xxx.d.ts文件,内部可以随意定义任何类型,但是不能包含任何exportimport语句,例如:

/*~ 
*~ 全局函数
*/
declare function myLib(a: string): string;
declare function myLib(a: number): number;

/*~
*~ 全局类型
*/
interface Person {
name: string;
age: number;
}

/*~
*~ 全局对象
*/
declare namespace myLib {
/*~
*~ myLib.version
*/
const version: string;

/*~
*~ new myLib.Cat();
*/
class Cat {
constructor(n: number);
readonly age: number;
purr(): void;
}

/*~
*~ const a: myLib.CatSettings = { weight: 5, name: "Maru" };
*/
interface CatSettings {
weight: number;
name: string;
tailLength?: number;
}

/*~
*~ myLib.checkCat(c, v);
*/
function checkCat(c: Cat, s?: VetID);
}

也可以直接定义Window上的变量、方法等。

interface Window {
a: string;

myFn: VoidFunction;
}