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

说明

普通的.ts文件是局部的 只有.d.ts文件是全局的

全局

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

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

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

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

不推荐的写法

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

ts 复制代码
const A = 1
type B = 2

模块

ts 复制代码
// xxx.d.ts
declare module 'A' {
  export const a = 1
}
ts 复制代码
// 其他文件
import {a} from 'A'

如果需要导入其他模块

ts 复制代码
// 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
}
相关推荐
后除7 小时前
从零到一: 创建一个 TypeScript 7 项目
前端·webpack·typescript
小磊哥er1 天前
深入解构Claude Code - 第 10 篇 · 高级能力
typescript·ai编程
小磊哥er1 天前
深入解构Claude Code - 第 9 篇 · 怎么给它加功能
typescript·ai编程
FungLeo1 天前
成为全栈·Node 后端篇·后端工程从零搭建:TypeScript、目录与热更新
javascript·typescript·node 后端
梅雅达编程笔记1 天前
实战:用Harness做一个自动化日报Agent
typescript·实战教程·deepseek·harness·自动化agent
AbelTomato2 天前
博客评论系统搭建回顾
javascript·typescript·cloudflare·supabase·hyperdrive
用户0934077735142 天前
HarmonyOS WPS Open SDK 实践:registerApp 鉴权与就绪门禁
android·typescript·harmonyos
穗余2 天前
Typescript let和var区别
前端·javascript·typescript
苏灿烤鱼2 天前
AI总改崩你的代码?4.6万星GitNexus架构深拆
typescript·开源·agent