9
votes

I got below TypeScript error when tried to use side component (outside of project directory):

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>'.

My WebStorm IDE did not detect this error; in was outputted in console when I ran Webpack with TypeScript loader.

The error occurs 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;
}

As follows from ui-kit-libary-in-development name, this is not npm-dependency yet, so it is not inside node_modules for now.

It was exclusively TypeScript error; although ts-loader casts this error, Webpack builds my project and compiled JavaScript works correctly. This error will disappear if to do one of below actions:

  • Move SimpleCheckbox.vue to same directory as SkipProjectInitializationStepPanel.ts and import it as import SimpleCheckbox from './SimpleCheckbox.vue';
  • Remove SimpleCheckbox from @Component({ template, components: { SimpleCheckbox } }) and leave only @Component({ template, components: {} }) (off course, SimpleCheckbox will no be rendered in this case, but it proves that problem is not in SkipProjectInitializationStepPanel).
  • Move ui-kit-libary-in-development to node_modules of main project and remove node_modules from ui-kit-libary-in-development (if don't remove, nothing will change).

Unfortunately, I could not reproduce this problem. For some reason below try of reproduction works without errors:

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>

All clues what I found is this comment in issue Setting components in Component decorator causes Typescript 2.4 error:

Side components should add .d.ts for it to work AFAIK.

Nick Messing

From this clue, the following question arising:

  • Where I should to create .d.ts - in my main project or dependency? Most likely in main project, but if it so, why I can import side components in third-party libraries like vuetify? Because there is .d.ts there!
  • How I need to declare new Vue component in .d.ts? Some tutorial or example?

Source files for bounty

Because I could not reproduce this problem and my project still is raw (has not got commercial value yet), I can share it by Google Drive (link for downloading zip archive). All node_modules are included, just run npm run developmentBuild in main-project directory.

If you are worry about potential viruses, you can also get source files in this repository, but because it is does not include node_modules, for reproducing it's required to execute npm install in both main-project and dependency directories.

2
" was outputted in console when I ran Webpack with TypeScript loader." how do you run it? what is the command and at what folder?acdcjunior
@acdcjunior, directory: "path/where/you/unzipped/**main-project**", command: npm run developmentBuild.Takeshi Tokugawa YD

2 Answers

13
votes

This has become quite a long answer. If you don't have time to read it all there's a TL;DR at the end.


Analysis

Error Message

At first I didn't really understand why TypeScript mentioning VueClass<Vue> and complaining about the template property. However, when I looked at the type definitions for the Component decorator, things became a bit clearer:

vue-class-component/lib/index.d.ts (parts omitted)

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;

What we can see here is that Component has two signatures. The first one to be used like you did, and the second one without options (@Component class Foo).

Apparently the compiler thinks our usage doesn't match the first signature so it must be the second one. Therefore we end up with an error message with VueClass<Vue>.

Note: In the latest version (3.6.3), TypeScript will actually display a better error, stating both overloads and why they don't match.

Better Error Message

The next thing I did was temporarily comment out the second function declaration in main-project/node_modules/vue-class-component and sure enough we get a different error message. The new message spans 63 lines so I figured it wouldn't make sense to include it in this post as a whole.

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'.

As you can see the error message is quite hard to read and doesn't really point to a specific problem. So instead I went ahead and started reducing the complexity of the project in order to understand the issue better.

Minimal Example

I'll spare you the whole process which involved lots of trial and error. Let's jump directly to the result.

Structure

├─ main-project
│  ├─ node_modules // installed packages listed below (without sub-dependencies)
│  │     [email protected]
│  │     [email protected]
│  │     [email protected]
│  │     [email protected]
│  │     [email protected]
│  │     [email protected]
│  │     [email protected]
│  ├─ SkipProjectInitializationStepPanel.ts
│  ├─ tsconfig.json
│  └─ webpack.config.js
└─ dependency
   ├─ node_modules // installed packages listed below (without sub-dependencies)
   │     [email protected]
   └─ 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 {}

When running this example from main-project with npm run webpack, we get the exact same error as before. Mission accomplished.

What's Happening?

While I was removing parts of the project to get it down to this minimal example, I learned something very interesting.

You might have noticed the import 'vuex' I've added to SkipProjectInitializationStepPanel.ts. In the original project vuex is of course imported from different places (e.g. main-project/Source/ProjectInitializer/Store/Store.ts) but that's not important for reproducing the issue. The crucial part is that main-project imports vuex and dependency doesn't.

To find out why importing vuex causes this issue, we have to look at the type definitions of vuex.

vuex/types/index.d.ts (first few lines)

import _Vue, { WatchOptions } from "vue";

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

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

Here we are interested in the second import. The comment actually gives us a hint already: augment typings of Vue.js.

vuex/types/vue.d.ts (parts omitted)

import { Store } from "./index";

// ...

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

And here we have the culprit. The vuex types make use of declaration merging to add $store to the Vue interface of vue. It seems that this augmentation only happens to "local" types in the same node_modules as vuex. Because main-project has the augmented Vue and dependency has the original one, the two don't match.

TS Loader

During all my testing I couldn't reproduce the problem with just tsc. Apparently ts-loader does something differently causing this issue. It could have to do with it using Webpack for module resolution or it could be something entirely different. I don't know.

Solution Approaches

I have some ideas how this problem could be solved or worked around. Although these are not necessarily ready-to-use solutions but rather different approaches and ideas.

Add vuex to dependency

As removing vuex from main-project isn't really an option, the only thing we can do to make both Vue interfaces match, is include vuex in dependency as well.

The odd thing here is that I was able to get this fix working in my minimal example but not in the original project. I haven't figured out why that is.

In addition to that, it's not very elegant and you might have to import vuex from every file that you reference from main-project.

Use a shared node_modules

Having a shared node_modules folder means both projects use the same vue so this problem goes away. Depending on your requirements it might be a good solution to organize the two projects in a way that they share the same node_modules folder. You might also want to take a look at tools like Lerna or Yarn workspaces which can help with this.

Consume dependency as a package

You say that dependency is not [an] npm-dependency yet. Maybe it's time to make it one. Similarly to a shared node_modules directory this would result in both projects using the same vue installation which should fix the issue.

Investigate further

As mentioned before, this only happens with ts-loader. Maybe there is something that can be fixed or configured in ts-loader to avoid this problem.

TL;DR

main-project imports vuex while dependency doesn't. vuex augments the Vue interface using declaration merging adding a $store property to it. Now the Vue from one project doesn't match Vue from other causing an error.

0
votes

As @lukasgeiter said,

Apparently ts-loader does something differently causing this issue.

Error will disappear, if delegate Type Check process to fork-ts-checker-webpack-plugin.