类型声明及扩展
ts的类型声明有两个特征:
- 在ts开发中,为了使用一些只有js版本的库,可以通过使用类型声明,在ts文件中直接使用库。
- 类型声明的代码在编译后会被删除,不会影响真正的代码
注意点
当前文件中使用了export关键字,为局部文件,需要在该文件中扩展全局变量
export{}
declare global {
interface String {
double(): string;
}
}
文件里不包含export时,为全局文件
// 直接声明,但是不能有export
declare interface Fn<T = any> {
(...arg: T[]): T
}
// 如果加了export 就需要另外import引入
tsconfig.json
如果类型声明文件没有起作用,需要注意在tsconfig.json文件下的"include"配置项
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2015",
"outDir": "lib",
// ...
},
"include": [ // 告诉 TS 需要编译的目录,默认会编译所有根目录下的文件
"src/**/*", // 告诉 TS 只需要编译 src 目录下的所有 .ts 文件
"typings/**/*.d.ts" // 告诉 TS 还需要编译 typings 目录下的所有 .d.ts 文件
],
"types": ["vite/client", "element-plus/global"], // 加载的声明文件包
"typeRoots": ["./node_modules/@types/", "src/types"],// 声明文件目录,默认是node_modules/@types
}
