Ts

.d.ts

.d.ts 文件是 TypeScript 中的类型声明文件,专门用于声明类型信息。它们通常用于以下情况:

  1. 声明全局类型:在项目的任何地方都可以使用这些类型,而不需要显式地导入。
  2. 为 JavaScript 库提供类型定义:当你使用的库是用 JavaScript 编写的,没有内置的 TypeScript 类型时,你可以通过 .d.ts 文件为其提供类型定义。
  3. 扩展现有的模块类型:例如在你的例子中,扩展 Vue Router 的 RouteMeta 接口。

为什么要用 .d.ts 后缀

  • 明确目的.d.ts 文件仅包含类型声明,没有具体实现代码。这使得文件的目的非常明确,即它们是用来描述类型结构的。
  • 避免编译: TypeScript 编译器会跳过 .d.ts 文件中的代码,不会将它们编译为 JavaScript。这减少了不必要的编译步骤。
  • 自动合并: TypeScript 会自动合并全局声明文件中的类型信息到项目的类型系统中,这使得这些类型可以在项目的任何地方使用。

实际应用

在你的项目中创建或修改 router.d.ts 文件,以扩展 RouteMeta 接口,使得访问 meta.title 时不报错:

  1. 创建 router.d.ts 文件
1
2
3
4
5
6
7
8
9
// src/router.d.ts
import 'vue-router';

declare module 'vue-router' {
  interface RouteMeta {
    title?: string;
    // 你可以在这里添加更多的自定义属性
  }
}
  1. 确保 TypeScript 项目设置:在 tsconfig.json 文件中确保包含了 src 目录,以便 TypeScript 能找到并使用你的声明文件。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src"]
}

使用扩展的类型

在你的 Vue 3 项目中,你可以安全地访问 meta.title

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { RouteLocationNormalized } from 'vue-router';
import { useTagBarStore } from '@/stores/tagBarStore';

function beforeEach(to: RouteLocationNormalized, from: RouteLocationNormalized, next: Function) {
  const tagBarStore = useTagBarStore();
  
  // 确保 title 存在并且是 string 类型
  if (to.meta.title) {
    tagBarStore.addTag({ name: to.meta.title, path: to.path });
  }

  next();
}

通过这种方式,你可以确保 meta.title 在你的项目中有正确的类型声明,并且在访问时不会报错。

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计