在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
}
相关推荐
浩星9 小时前
electron系列2:搭建专业Electron开发环境
javascript·typescript·electron
Z_Wonderful12 小时前
React react-app-env.d.ts是 TypeScript 的全局类型声明文件,它的作用
前端·react.js·typescript
落魄江湖行13 小时前
基础篇二 Nuxt4 路由守卫:页面访问控制
前端·typescript·nuxt4
落魄江湖行2 天前
入门篇八 Nuxt4页面元信息与 SEO:让搜索引擎爱上你的网站
前端·typescript·seo·nuxt4
LcGero2 天前
TypeScript 快速上手:前言
typescript·cocos creator·游戏开发
条tiao条2 天前
TypeScript 网络编程从零到一:net 模块全解析(入门专属)
javascript·网络·typescript
ZHENGZJM2 天前
前端基石:React + Vite + TypeScript 项目搭建
前端·react.js·typescript
曲幽2 天前
告别手写 API 胶水代码:FastAPI 与 Vue 的“契约自动机” OpenAPI 实战
python·typescript·vue·fastapi·web·swagger·openapi·codegen
@二进制3 天前
vue3+vant4+ts出现页面空白?甚至在App.vue的<template></template>中随便输入都无法显示?
前端·vue.js·typescript
桂森滨3 天前
Vue3+Pinia+Vite+TS 还原高性能外卖APP项目 4️⃣首页开发
前端·typescript·vue