TS扩展类型
扩展类型
-
以扩展
interface为例,type同理使用type的规则扩展,如typeA | typeB -
方式一:类型声明文件使用
declare关键字的,直接在项目类型声明文件进行扩展
// lib.dom.d.ts
declare var Document: {prototype: Document;new(): Document;
};// index.d.ts
// 扩展出一个name属性
declare interface Document {name: string;
}
// index.ts
let test: Document = document;
console.log(test.name); // 编译通过,运行时必报错
⚠️ 这里是演示,不要瞎扩展
- 方式二:通过模块导出的扩展类型,通过继承或扩展模块
// 演示axios的CreateAxiosDefaults扩展
// create方法的类型:create(config?: CreateAxiosDefaults): AxiosInstance;
axios.create(config);
config.name; // ❌ 此时绝对报错// 方式一:通过继承扩展
// type.ts
import type { CreateAxiosDefaults } from "axios";
export interface AxiosConfig<D = any> extends CreateAxiosDefaults<D> {name: string;
}
// index.ts
import axios form "axios";
const customConfig: AxiosConfig<any> = {};
customConfig.name // ✅
axios.create(customConfig); // ✅// 方式二:通过类型声明文件扩展即对模块下的CreateAxiosDefaults方法扩展
// index.d.ts
import "axios"; // 这里需要引入axios是因为,`declare module`会进行覆盖
declare module "axios" {name: string;
}
// index.ts
import type { CreateAxiosDefaults } from "axios";
const customConfig: CreateAxiosDefaults<any> = {};
customConfig.name; // ✅
axios.create(customConfig); // ✅
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
