Typescript dynamically declare named exports in d.ts
P粉642436282
P粉642436282 2024-02-26 11:58:58
0
1
443

I made a component library for VueJs in TypeScript and I want to be able to use them globally in my Vue instance (using Vue.use(library)) or use them one by one (using Vue Named imports in components)

It works fine, but I have some problems using TypeScript when I want to dynamically declare all the components in the index.d.ts file (because there are many components and I don't want to Manual execution)

So this is valid:

import { Component1, Component2 } from 'my-library';

declare module 'my-library' {
  declare const lib: PluginFunction<any>;
  export default lib;

  export { Component1, Component2 } from 'my-library';
}

But I'm looking for a way to do this for all components without importing and exporting them one by one.

I tried something like this:

...
export * from 'my-library'
...

or

import * as components from 'my-library';

declare module 'my-library' {
  declare const lib: PluginFunction<any>;
  export default lib;

  Object.entries(components).forEach(([componentName, component]) => {
    export { component as componentName };
    // or
    // export { component };
  })
}

But it doesn't work, when I execute import { Component1 } from 'my-library' I get TS error:

"Unable to resolve symbol 'Component1' TS2614: Module 'my-library' does not export member 'Component1'. Are you planning to use "import Component1 from "my-library""? ”

ps: If I use //@ts-ignore before importing, everything works fine.

Any ideas?

P粉642436282
P粉642436282

reply all(1)
P粉739886290

My guess is that this is because TS needs something to do "type checking" at build time. In other words, TS is more restrictive than JS, which is one of the prime examples of lost flexibility, since it wants to be defined at build time rather than runtime.

In short, you can't do this. The only thing you can do is export everything in the keyed object, but that means when you import it into another file, you have to get the whole thing and not just a part of it.

File.vue



Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template