在ts中定义全局和模块的变量和类型

98 阅读1分钟

说明

普通的.ts文件是局部的 只有.d.ts文件是全局的
.d.ts仅存在于编译时 仅用于声明类型
也可以考虑用tsconfig.json+打包工具的别名 以简便的方式访问指定的文件

全局

// xxx.d.ts
// 只能在文件顶部导入全局模块
import type { CSSProperties } from 'react'

// 将本文件声明为模块
export {}

// 在模块外的不会被导出 但是可以被模块内引用
type C = 1

// 拓展已有的全局模块
declare global {
   // export 写不写没影响
   type B = 2
   type D = C
}

不推荐的写法

老版本ts的语法 当时还没有模块 全在用namespace

type B = 2

模块

// xxx.d.ts
declare module 'A' {
  export type T = 1
}
// 其他文件
import { T } from 'A'

如果需要导入其他模块

// xxx.d.ts
// 不能在模块外部import 或 export

// 写在外面不会被视作模块的内容 可以被模块里引用
type B = string
declare module 'A' {
  // 可以导入全局模块 必须写在模块内部的顶部
  import { CSSProperties } from 'react'
  
  export type Style = CSSProperties
  // 写不写export 都可以 但export会使编辑器更好地处理引用
  type A = 1
  type B = B
}