ts书写全局使用type/interface的xxx.d.ts

434 阅读1分钟

本篇文章主要讲解如何配置一个全局的XXX.d.ts,以避免频繁使用到的type/interface 总是被使用的地方进行import type { x } from xxx引入

首先,在项目的任何地方创建一个xxx.d.ts的文件,eg: src/types/index.d.ts 项目根目录的 tsconfig.json 文件可以配置 TypeScript。而include 属性包含了所需要校验 ts 的文件,会将 xxx.d.ts 类型文件中的类型注册成全局的,举个栗子:

创建文件 src/types/index.d.ts

interface detailItemType {
  label: string
  prop: string
  span?: number
  type?: string
  line?: boolean
  slot?: boolean
  dicData?: { [T: string]: any }[]
  formatter?: (value: any, index: number) => {}
}

interface detailDataType {
  [T: string]: any
  id?: string
}
// 列表数据配置类型
type lineOPtionType = detailItemType[]

tsconfig.json配置

{
   "include": ["src/types/index.d.ts"]
   // 或者
   "include": ["src/**/*.d.ts"]
}

eslint配置 会有报错 'xxx' is not defined.eslint[no-undef]

image.png 此处可修改eslint的配置,关闭no-undef配置,关闭原因:

使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。

//.eslintrc.cjs
  rules: {
    ...
    'no-undef': 0,
  }

image.png eslint.org/docs/latest…

使用对比:

// 配置前:
import '@/types/indexd.ts'
const detail = ref<detailDataType>({})
const lineOPtion = ref<lineOPtionType>([])

// 全局配置后:
const detail = ref<detailDataType>({})
const lineOPtion = ref<lineOPtionType>([])