typescript - 如何手动(本地)包含 .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 如何与打字稿一起工作。也许我只是在配置文件中犯了一个错误。
解决方案
typeRoots
指的是目录,而不是文件。另外,它指的是包含类型 packages的文件夹。
types 包是一个文件夹,其中包含一个名为 index.d.ts 的文件,或者一个包含 package.json 且具有 types 字段的文件夹。- typescriptlang.org
通常这是./node_modules/@types
文件夹,也是typeRoots
option 的默认值。
对于您的情况,最好使用该include
选项而不是typeRoots
.
{
"include": [
"./types",
/* other .ts or .d.ts source code containing folders here */
],
"compilerOptions": { ... }
}
推荐阅读
- scala - Spark SQL 结构化数据写入原子文件
- elasticsearch - 为什么 Sphinxsearch 没有像 elasticsearch 文档这样的简单示例的简单文档?
- javascript - ng-bootstrap datepicker - 设置默认年份
- excel - 从多个条件返回的多个值
- java - 即使没有语法错误,Eclipse 程序也不会运行
- ios - NSCache - 丢弃内容
- paypal - 自动计费在荷兰可用吗?
- excel - 找到最小值并粘贴在表格的末尾 VBA
- api - Google Cloud Platform 合作伙伴互连 API - 只有获得批准的合作伙伴才能创建类型为 PARTNER 的互连
- bash - 将数据从 for 循环传递到 zenity 进度