前端 - ts - - declare声明类型

发布于:2025-04-02 ⋅ 阅读:(103) ⋅ 点赞:(0)

 在使用typeScript的项目中 需要声明属性类型 单独的局部属性 可以直接在当前文件中声明 全局属性需要在项目根目录下新建.d.ts文件 vite会自动识别.d.ts类型文件

在该文件中使用declare声明类型有三种写法

1、在某种类型的文件中声明

2、声明window上的属性类型

3、全局声明

一、在某种类型文件中声明

以下代码是告诉ts 每个.vue文件是合法模块 默认到处一个vue组件 避免impot导入某个组件时 ts认为当前组件是未定义的模块(vue3+ts的基石)

// 在某种类型的文件中声明
declare module '*.vue' {
  import type { DefineComponent } from 'vue';
  // 完整写法
  const component: DefineComponent<
    {
      msg: string;       // 定义 props 类型
      count?: number;    // 可选 prop
    },
    {},                  // 不定义 data
    any,                 // 不限制方法上下文
    {},                  // 不定义 computed
    {
      onClick(): void;   // 定义 emits 类型
    }
  >;
  //精简写法
  const component: DefineComponent<{},any,{}>
  export default component;
}

二、声明window上的属性

用于当项目中引入的第三方库或cdn的sdk 属性会挂载到window上 严格明确作用于window对象. 适用于浏览器环境

// index.html 通过script引入第三方库
<script src='xxx'></script>

// .d.ts
declare global {
 interface window{
    xxx:any
  }
}

//index.vue 使用
window.xxx

三、全局声明

也会适用于通过script引入第三方库 顾名思义 任何环境都会声明(浏览器环境、node环境等)没有那么严格 

// .d.ts
// 变量简易写法
declare const xxx:any
// 方法完整写法
declare const xxx: {
  // options代表传参 可以不为any类型 具体类型根据情况自己定义
  new (options:any): {
    // 回调函数:(参数)=> 返回值
    fn1:()=>void
    fn2:(val:any)=> number
  }
}

// index.vue 直接使用或new一个新对象
const myObj = xxx
const newObj = new xxx()


网站公告

今日签到

点亮在社区的每一天
去签到