icodex | 前端技术博客 | 专注 React、TypeScript、AI 与性能优化 Blog

icodex - 个人网站

马上订阅 icodex | 前端技术博客 | 专注 React、TypeScript、AI 与性能优化 Blog RSS 更新: https://icodex.me/atom.xml

TypeScript全局类型定义的方式

2024年4月1日 08:00

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...

剩余内容已隐藏

查看完整文章以阅读更多