首页 > 解决方案 > 如何手动(本地)包含 .d.ts 文件?或者如何使用用户定义的 .d.ts 文件?

问题描述

我正在研究 nuxt.js,由于某种原因,我想像这样扩展 Vue 的实例:

import Vue from 'vue'

Vue.prototype.$myProp = 'test'

const app = new Vue()

console.log(app.$myProp)

按照https://vuejs.org/v2/guide/typescript.html#Augmenting-Types-for-Use-with-Plugins的指南,我在 types/test.d.ts 创建了一个文件,内容如下:

declare module 'vue/types/vue' {
  interface Vue {
    $myProp: string;
  }
}

但是,我不知道如何使它工作。

我在我的 VSCode 中收到错误。当我执行 tsc(版本 3.7.2)时也会收到错误:

index.ts:14:17 - error TS2339: Property '$test' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.

14 console.log(app.$test)

我尝试在根目录中使用 tsconfig.json ,但不起作用:

{
    "compilerOptions": {
        "typeRoots": [
            "types/test.d.ts"
        ]
    }
}

我也尝试过插入这样的参考,但现在可以工作了:

///<reference path="types/test.d.ts"/>

当然,我不想在每个文件中都包含这个声明文件。有没有办法在整个项目中启用声明?

我不知道 VSCode 如何与打字稿一起工作。也许我只是在配置文件中犯了一个错误。

标签: typescript

解决方案


typeRoots指的是目录,而不是文件。另外,它指的是包含类型 packages的文件夹。

types 包是一个文件夹,其中包含一个名为 index.d.ts 的文件,或者一个包含 package.json 且具有 types 字段的文件夹。- typescriptlang.org

通常这是./node_modules/@types文件夹,也是typeRootsoption 的默认值。

对于您的情况,最好使用该include选项而不是typeRoots.

{
  "include": [
    "./types",
    /* other .ts or .d.ts source code containing folders here */
  ],
  "compilerOptions": { ... }
}

推荐阅读