一、.d.ts是干嘛用的
.d.ts文件是ts用来声明变量,模块,type,interface等等的,那在这种后缀的ts文件声明这些东西和在纯ts文件声明这些东西又什么区别呢?
在.d.ts声明变量或者模块等东西之后,在其他地方可以不用import导入这些东西就可以直接用。
但是也不是说创建了.d.ts文件,里面声明的东西就能生效了,毕竟归根到底也是.ts文件,需要预编译,所以需要在tsconfig.json文件里面的include数组里面添加这个文件,比如我们在vue3+Ts项目中的tsconfig.json中可以做如下配置:
{
"compilerOptions": {
"baseUrl": ".",
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"noImplicitThis": false, // js/ts 混用时设为false
"allowJs": true,
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"lib": ["esnext", "dom"],
"types": [
"@dcloudio/types",
"pinia-plugin-persist-uni",
"miniprogram-api-typings"
],
"typeRoots": ["./node_modules/@types/","./node_modules/@dcloudio/types/", "./types"],
"paths": {
"@/*": ["src/*"],
"@vant/weapp/*": ["path/to/node_modules/@vant/weapp/dist/*"]
}
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"src/typings/*.d.ts",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
include数组里面可以不用写.d.ts文件的绝对路径,可以通过glob通配符,匹配这个文件所在的文件夹或者是“祖宗级别”文件夹.
具体tsconfig.json配置请看这www.tslang.cn/docs/handbo…
其中 src/**/*.vue,就表 示在vue文件中,使用在.d.ts中声明的type和interface时,是不需要单独import的,可以直接使用。比如在src下@types中有test.d.ts
// test.d.ts
declare interface Obj {
a:number,
b:string
}
我们在vue文件中,可以直接使用:
<script lang='ts' setup>
import {reactive} from 'vue'
// 可以直接使用Obj
const obj = reactive<Obj>({
a:1,
b:'q'
})
</script>
二、declare用法
d.ts 文件中的顶级声明必须以 declare 或 export 修饰符开头.
通过declare声明的类型或者变量或者模块,在include包含的文件范围内,都可以直接引用而不用去import或者import type相应的变量或者类型。
declare声明一个类型
declare type Asd = {
a:number
}
在include包含的文件范围内,可以直接使用Asd这个type
declare声明一个模块
declare module '*.css'
declare module '*.less'
declare module '*.png'
在编辑ts文件的时候,如果你想导入一个.css/.less/.png格式的文件,如果没有经过declare的话是会提示语法错误的
declare声明一个作用域
在test.d.ts中声明:
declare namespace API {
interface ResponseList {
code:number,
}
}
在vue文件中可以直接使用,不用import
index.vue
const res = ref<API.ResponseList>({})