[英]Vue&TypeScript: how to avoid error TS2345 when import implemented in TypeScript component outside of project directory?
尝试使用辅助组件(项目目录外部)时出现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
名称中可以ui-kit-libary-in-development
,这还不是npm-dependency,因此它现在不在node_modules
内部。
这完全是TypeScript错误。 尽管ts-loader
会抛出此错误,但Webpack会构建我的项目,并且已编译的JavaScript可以正常工作。 如果执行以下操作之一,此错误将消失:
SimpleCheckbox.vue
与SkipProjectInitializationStepPanel.ts
移至同一目录,并将其作为import SimpleCheckbox from './SimpleCheckbox.vue';
@Component({ template, components: { SimpleCheckbox } })
删除SimpleCheckbox
并仅保留@Component({ template, components: {} })
(当然,在这种情况下,将不会呈现SimpleCheckbox
,但事实证明该问题是不在SkipProjectInitializationStepPanel
)。 ui-kit-libary-in-development
node_modules
主项目的node_modules
,并从ui-kit-libary-in-development
删除node_modules
(如果不删除,则不会有任何变化)。 不幸的是,我无法重现此问题。 由于某些原因,下面的重试效果没有错误:
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>
我发现的所有线索都是该问题的注释, 在组件装饰器中设置组件会导致Typescript 2.4错误 :
侧面组件应添加.d.ts才能正常运行。
从这个线索中,产生了以下问题:
.d.ts
? 最有可能在主项目中,但是如果是这样,为什么我可以在vuetify
类的第三方库中导入辅助组件? 因为那里有.d.ts
! .d.ts
声明新的Vue组件? 一些教程或示例? 因为我无法重现此问题,并且我的项目仍然是原始项目(尚未获得商业价值),所以我可以通过Google云端硬盘( 下载zip存档的链接)进行共享。 所有的node_modules
都包括在内,只需在main-project
目录中运行npm run developmentBuild
。
如果您担心潜在的病毒,也可以在此存储库中获取源文件,但是由于它不包含node_modules
,因此,要进行复制,需要在main-project
和dependency
目录中执行npm install
。
这已经是一个很长的答案。 如果您没有时间阅读所有内容,请在末尾找到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 {}
当使用npm run webpack
从main-project
运行此示例时,我们得到与以前完全相同的错误。 任务完成。
当我删除项目的各个部分以简化为这个最小的示例时,我学到了一些非常有趣的东西。
您可能已经注意到我已添加到SkipProjectInitializationStepPanel.ts
的import 'vuex'
。 在原始项目中, vuex
当然是从不同位置导入的(例如main-project/Source/ProjectInitializer/Store/Store.ts
),但这对于重现该问题并不重要。 关键部分是main-project
导入vuex
而dependency
不导入 。
要找出为什么导入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
添加到vue
的Vue
接口。 看来,这增强只发生在同一个“本地”类型node_modules
为vuex
。 因为main-project
具有增强的Vue
而dependency
具有原始Vue
,所以两者不匹配。
在我所有的测试过程中, tsc
无法重现该问题。 显然ts-loader
所做的事情有所不同,导致了此问题。 它可能与使用Webpack进行模块解析有关,也可能完全不同。 我不知道。
我有一些想法可以解决或解决此问题。 尽管这些不一定是立即可用的解决方案,而是不同的方法和想法。
vuex
添加到dependency
因为从main-project
删除vuex
并不是一个真正的选择,所以我们要做的唯一一个使两个Vue
接口都匹配的方法就是将vuex
也包含在dependency
中。
奇怪的是,我能够在最小的示例中获得此修复程序,但在原始项目中却没有。 我还不知道为什么。
除此之外,它还不是很优雅,您可能必须从main-project
引用的每个文件中导入vuex
。
node_modules
具有共享node_modules
文件夹的手段这两个项目使用相同的vue
所以这个问题消失。 根据您的要求,将两个项目共享一个相同的node_modules
文件夹来组织它们可能是一个很好的解决方案。 您可能还想看一下Lerna或Yarn工作区之类的工具,它们可以为您提供帮助。
dependency
作为包使用 您说dependency
不是npm-dependency 。 也许是时候做到这一点了。 与共享的node_modules
目录类似,这将导致两个项目使用相同的vue
安装,这将解决此问题。
如前所述,这仅在ts-loader
发生。 也许可以在ts-loader
固定或配置某些东西来避免此问题。
main-project
导入vuex
而没有dependency
。 vuex
使用声明合并来增强Vue
接口, 并在其中添加$store
属性。 现在Vue
从一个项目不匹配Vue
其他导致错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.