在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
}
相关推荐
IT飞牛1 小时前
【MCP开发】Nodejs+Typescript+pnpm+Studio搭建Mcp服务
typescript·mcp
烛阴9 小时前
告别 any!用联合类型打造更灵活、更安全的 TS 代码
前端·typescript
知识分享小能手1 天前
Vue3 学习教程,从入门到精通,Vue 3 + Tailwind CSS 全面知识点与案例详解(31)
前端·javascript·css·vue.js·学习·typescript·vue3
Running_C2 天前
从「救命稻草」到「甜蜜的负担」:我对 TypeScript 的爱恨情仇
前端·typescript
正义的大古2 天前
Vue 3 + TypeScript:深入理解组件引用类型
前端·vue.js·typescript
孟陬2 天前
bun 单元测试问题之 TypeError: First argument must be an Error object
typescript·单元测试·bun
孟陬2 天前
CRA 项目 create-react-app 请谨慎升级 TypeScript
react.js·typescript
孟陬2 天前
TypeScript v5 一个非常有用的新语法:“const 类型参数”
typescript
我是火山呀5 天前
React+TypeScript代码注释规范指南
前端·react.js·typescript