代码之家  ›  专栏  ›  技术社区  ›  user764754

如何将TypeScript与vue一起使用而不使用模块

  •  2
  • user764754  · 技术社区  · 8 年前

    在里面 package.json 我有

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

    这让我 index.d.ts, vue.d.ts so on 在里面 node_modules\vue\types .起初,我的问题是找不到vue( (TS) Cannot find name 'Vue' )当你做这样的事情时 new Vue({...}); .阅读后 this 线程I通过添加 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
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   user764754    8 年前

    我有以下基本功能 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 inaccessible module 但TypeScript可以传输并运行良好。

    推荐文章