首页 > 解决方案 > Vue&TypeScript:在项目目录外的 TypeScript 组件中实现导入时如何避免错误 TS2345?

问题描述

尝试使用侧组件(项目目录之外)时出现以下 TypeScript 错误:

TS2345: Argument of type '{ template: string; components: { SimpleCheckbox: typeof SimpleCheckbox; }; }' 
is not assignable to parameter of type 'VueClass<Vue>'.
Object literal may only specify known properties, and 'template' does not exist in type 
'VueClass<Vue>'.

我的 WebStorm IDE 没有检测到这个错误;当我使用 TypeScript 加载程序运行 Webpack 时,in 在控制台中输出。

错误发生在:

import { Vue, Component, Prop } from 'vue-property-decorator';
import template from './SkipProjectInitializationStepPanel.pug';
import SimpleCheckbox from './../../../../ui-kit-libary-in-development/UiComponents/Checkboxes/MaterialDesign/SimpleCheckbox.vue';


@Component({ template, components: { SimpleCheckbox } }) // here !
export default class SkipProjectInitializationStepPanel extends Vue {
  @Prop({ type: String, required: true }) private readonly text!: string;
}

ui-kit-libary-in-development名字来看,这还不是npm-dependency,所以暂时不在里面node_modules

这完全是 TypeScript 错误;虽然ts-loader抛出了这个错误,但 Webpack 构建了我的项目并且编译的 JavaScript 可以正常工作。如果执行以下操作之一,此错误将消失:

不幸的是,我无法重现这个问题。出于某种原因,下面的复制工作尝试没有错误:

MainProject/src/Application.vue

<template lang="pug">
  PageOne
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator';
  import PageOne from './PageComponents/PageOne'

  @Component({ components: { PageOne }})
  export default class Application extends Vue {
    private created(): void {
      console.log('Done.');
    }
  }
</script>

MainProject/src/PageComponents/PageOne.ts

import { Vue, Component, Prop } from 'vue-property-decorator';
import template from './PageOne.pug';
import Button from './../../../UiKitLibraryStillInDevelopment/UiComponents/Buttons/Button.vue';


@Component({ template, components: { Button } })
export default class SkipProjectInitializationStepPanel extends Vue {}

MainProject/src/PageComponents/PageOne.pug

.RootElement
  Button(:text="'Click me'")

ui-kit-libary-in-development/UiComponents/Buttons/Button.vue

<template lang="pug">
  button {{ text }}
</template>


<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator';

  @Component
  export default class SimpleCheckbox extends Vue {
    @Prop({ type: String, required: true }) private readonly text!: string;

    private created(): void {
      console.log('OK!');
      console.log(this.$props);
    }
  }
</script>

我发现的所有线索都是问题Setting components in Component decorator 中的评论导致 Typescript 2.4 错误

侧面组件应添加 .d.ts 以使其正常工作。

尼克·梅辛

从这个线索,产生了以下问题:


赏金的源文件

因为我无法重现这个问题,而且我的项目仍然是原始的(尚未获得商业价值),我可以通过 Google Drive 共享它(下载 zip 存档的链接)。所有node_modules都包括在内,只需npm run developmentBuildmain-project目录中运行。

如果您担心潜在的病毒,您也可以在此存储库中获取源文件,但由于它不包含node_modules,因此需要npm installmain-projectdependency目录中执行。

标签: typescriptvue.jsvue-componenttypescript-decoratortypescript-definitions

解决方案


这已经成为一个很长的答案。如果您没有时间阅读所有内容,则末尾有 TL;DR


分析

错误信息

起初我并不真正理解为什么 TypeScript 会提到VueClass<Vue>和抱怨该template属性。然而,当我查看Component装饰器的类型定义时,事情变得更加清晰:

vue-class-component/lib/index.d.ts(部分省略)

declare function Component<V extends Vue>(options: ComponentOptions<V> & ThisType<V>): <VC extends VueClass<V>>(target: VC) => VC;
// ...
declare function Component<VC extends VueClass<Vue>>(target: VC): VC;

我们在这里可以看到Component有两个签名。第一个像你一样使用,第二个没有选项(@Component class Foo)。

显然编译器认为我们的用法与第一个签名不匹配,所以它必须是第二个。因此,我们最终会收到一条错误消息VueClass<Vue>

注意:在最新版本 (3.6.3) 中,TypeScript 实际上会显示一个更好的错误,说明两个重载以及它们不匹配的原因。

更好的错误信息

我做的下一件事是暂时注释掉第二个函数声明main-project/node_modules/vue-class-component,果然我们得到了不同的错误消息。新消息跨越 63 行,所以我认为将它作为一个整体包含在这篇文章中是没有意义的。

ERROR in /tmp/main-project/InitializeProjectGUI__assets/SingletonComponents/SkipProjectInitializationStepPanel/SkipProjectInitializationStepPanel.ts
../InitializeProjectGUI__assets/SingletonComponents/SkipProjectInitializationStepPanel/SkipProjectInitializationStepPanel.ts
[tsl] ERROR in /tmp/main-project/InitializeProjectGUI__assets/SingletonComponents/SkipProjectInitializationStepPanel/SkipProjectInitializationStepPanel.ts(10,24)
      TS2322: Type '{ SimpleCheckbox: typeof SimpleCheckbox; }' is not assignable to type '{ [key: string]: VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...>; }'.
  Property 'SimpleCheckbox' is incompatible with index signature.
    Type 'typeof SimpleCheckbox' is not assignable to type 'VueConstructor<Vue> | FunctionalComponentOptions<any, PropsDefinition<any>> | ComponentOptions<never, any, any, any, any, Record<string, any>> | AsyncComponentPromise<any, any, any, any> | AsyncComponentFactory<...>'.
      Type 'typeof SimpleCheckbox' is not assignable to type 'VueConstructor<Vue>'.
        Types of property 'extend' are incompatible.
          Type '{ <Data, Methods, Computed, PropNames extends string = never>(options?: import("/tmp/dependency/node_modules/vue/types/options").ThisTypedComponentOptionsWithArrayProps<import("/tmp/depende...' is not assignable to type '{ <Data, Methods, Computed, PropNames extends string = never>(options?: import("/tmp/main-project/node_modules/vue/types/options").ThisTypedComponentOptionsWithArrayProps<import("/tmp/main-...'.
            ...
              Type 'import("/tmp/dependency/node_modules/vue/types/vnode").ScopedSlotReturnValue' is not assignable to type 'import("/tmp/main-project/node_modules/vue/types/vnode").ScopedSlotReturnValue'.
                Type 'VNode' is not assignable to type 'ScopedSlotReturnValue'.

如您所见,错误消息很难阅读,并没有真正指向特定问题。因此,我开始着手降低项目的复杂性,以便更好地理解问题。

最小的例子

我将为您省去涉及大量试验和错误的整个过程。让我们直接跳到结果。

结构

├─ main-project
│  ├─ node_modules // installed packages listed below (without sub-dependencies)
│  │     ts-loader@6.1.0
│  │     typescript@3.6.3
│  │     vue@2.6.10
│  │     vue-property-decorator@8.2.2
│  │     vuex@3.1.1
│  │     webpack@4.40.2
│  │     webpack-cli@3.3.9
│  ├─ SkipProjectInitializationStepPanel.ts
│  ├─ tsconfig.json
│  └─ webpack.config.js
└─ dependency
   ├─ node_modules // installed packages listed below (without sub-dependencies)
   │     vue@2.6.10
   └─ SimpleCheckbox.ts

main-project/tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "strict": true,
    "moduleResolution": "node"
  }
}

main-project/webpack.config.js

module.exports = {
    entry: './SkipProjectInitializationStepPanel.ts',
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.ts$/,
                loader: 'ts-loader'
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.js']
    }
};

main-project/SkipProjectInitializationStepPanel.ts

import { Component } from 'vue-property-decorator';
import 'vuex';

import SimpleCheckbox from '../dependency/SimpleCheckbox';

Component({ template: '', components: { SimpleCheckbox } });

dependency/SimpleCheckbox.ts

import Vue from 'vue';

export default class SimpleCheckbox extends Vue {}

main-projectwith运行此示例时npm run webpack,我们得到与以前完全相同的错误。任务完成。

发生了什么?

当我删除项目的一部分以将其归结为这个最小的示例时,我学到了一些非常有趣的东西。

您可能已经注意到import 'vuex'我添加到SkipProjectInitializationStepPanel.ts. 在原始项目vuex中当然是从不同的地方(例如main-project/Source/ProjectInitializer/Store/Store.ts)导入的,但这对于重现问题并不重要。关键部分是main-project导入vuexdependency导入。

要找出导入vuex导致此问题的原因,我们必须查看vuex.

vuex/types/index.d.ts(前几行)

import _Vue, { WatchOptions } from "vue";

// augment typings of Vue.js
import "./vue";

import { mapState, mapMutations, mapGetters, mapActions, createNamespacedHelpers } from "./helpers";

这里我们感兴趣的是第二个import。该评论实际上已经给了我们一个提示:增加 Vue.js 的类型

vuex/types/vue.d.ts(部分省略)

import { Store } from "./index";

// ...

declare module "vue/types/vue" {
  interface Vue {
    $store: Store<any>;
  }
}

在这里,我们有罪魁祸首。这些vuex类型利用声明合并来添加$store到. 似乎这种扩充只发生在与. 因为有增强的和有原始的,两者不匹配。Vuevuenode_modulesvuexmain-projectVuedependency

TS 装载机

在我所有的测试过程中,我无法仅用tsc. 显然ts-loader做了一些不同的事情导致了这个问题。它可能与使用 Webpack 进行模块解析有关,也可能完全不同。我不知道。

解决方法

我有一些想法如何解决或解决这个问题。尽管这些不一定是现成的解决方案,而是不同的方法和想法。

添加vuexdependency

由于删除vuexfrommain-project并不是一个真正的选择,我们唯一能做的就是让两个Vue接口匹配,也就是 include vuexin dependency

奇怪的是,我能够在我的最小示例中得到这个修复,但在原始项目中却没有。我还没弄清楚为什么会这样。

除此之外,它不是很优雅,您可能必须vuex从您引用的每个文件中导入main-project.

使用共享node_modules

拥有一个共享node_modules文件夹意味着两个项目都使用相同的vue,所以这个问题就消失了。根据您的要求,以共享同一node_modules文件夹的方式组织两个项目可能是一个很好的解决方案。您可能还想看看LernaYarn 工作区等工具,它们可以帮助解决这个问题。

作为dependency一个包使用

你说那dependency 还不是 [an] npm-dependency。也许是时候把它变成一个了。与共享目录类似,node_modules这将导致两个项目使用相同的vue安装,这应该可以解决问题。

进一步调查

如前所述,这只发生在ts-loader. 也许有一些可以修复或配置的东西ts-loader来避免这个问题。

TL;博士

main-project进口vuex而不进口dependency使用声明合并向其添加属性来vuex扩充Vue接口。现在,来自一个项目的项目与其他项目不匹配,导致错误。$storeVueVue


推荐阅读