typescript - 如何在 vue 和无模块的情况下使用 TypeScript

标签 typescript vue.js

package.json我有

"devDependencies": {    
   "vue": "2.5.16"
}

这给了我 index.d.ts, vue.d.tsso onnode_modules\vue\types .起初我遇到的问题是在执行类似 (TS) Cannot find name 'Vue' 的操作时找不到 vue ( new Vue({...});) .看完this线程我通过添加 custom.d.ts 来修复它文件:

import _vue = require('vue');

declare global {
    const Vue: typeof _vue;
}

并用 /// <reference path="../Declarations/custom.d.ts" /> 引用它

显然,原因是 vue 的声明是外部模块格式(使用 export ),如果没有使用模块系统,则需要全局模块。

但现在 IntelliSense 给我:"(TS) Cannot use 'new' with an expression whose type lacks a call or construct signature."构建失败。

我正在使用 TypeScript 2.8 和 outFile并且没有模块(只有 reference xml 注释)。

编辑:我以为我通过使用找到了答案

const Vue: typeof _vue.default;

这导致了 new Vue() 的错误声明走开。但是当我尝试声明一个 Vue 类型的变量时我得到 Cannot find name 'Vue'再次出错:

var app = new Vue({}); // Works
var app2:Vue = new Vue({}); // Doesn't work

最佳答案

我在 custom.d.ts 中获得了运行以下内容的基础知识:

import * as _vueIndex from "vue";
import * as _vue from "vue/types/vue";

declare global {
    const Vue: _vueIndex.VueConstructor; // related to vue.d.ts "export const Vue: VueConstructor;"

    namespace Vue {
        //type Vue = typeof _vueIndex.default; // For some reason this becomes VueConstructor interface instead of Vue interface
        type Vue = _vue.Vue;
        type CreateElement = _vueIndex.CreateElement;
        type CombinedVueInstance<Instance extends Vue, Data, Methods, Computed, Props> = _vue.CombinedVueInstance<Instance, Data, Methods, Computed, Props>;
        /*Other interfaces*/
    }
}

现在可以做类似的事情了:

var app: Vue.CombinedVueInstance<Vue.Vue, any, VmMethods, any, any> = new Vue({
    el: '#app',
    methods: new VmMethods()
});

console.log(app.toggleSidebar()); // toggleSidebar is a public function in VmMethods
console.log(app.nonExisting()); // ReSharper gives correct cannot resolve error but TypeScript still transpiles for some reason, which gives a run time error

ReSharper 仍然给出 Symbol Vue cannot be properly resolved, probably it is located in accessible module 但 TypeScript 可以正常转换和运行。

关于typescript - 如何在 vue 和无模块的情况下使用 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50163017/

相关文章:

vue.js - 在 Vuetify 和 Vue JS 中将 Prop 传递给 parent

javascript - 获取 JSON 数据 : Syntax error

angular - 如何在 Angular 8 的 Web Worker 中导入 typescript 模块?

javascript - 如何将 Node.js 异步流回调转换为异步生成器?

javascript - 如何使用 Vue.js 在同一个表中嵌套多个循环

javascript - 在 Vue 应用程序之外使用 Vue 电话号码组件

javascript - 如何从 JSON 对象中触发函数

typescript - 如何用 typescript 接口(interface)描述 mobx-state-tree 的模型?

javascript - Observable<Boolean> 方法在 catch block 后返回 null

javascript - 无法创建新的vue组件