Home > Back-end >  How can I export a default object with interfaces in it in TypeScript?
How can I export a default object with interfaces in it in TypeScript?

Time:01-13

import A from './A';
import type { AProps } from './A';

import B from './B';
import type { BProps } from './B';

export default {
    A, AProps,
    B, BProps
}

I want to export a default object with interfaces inside it.

The code above causes exception under vite because AProps and BProps variables are not defined in the output js file.

I tried another way which can solve this problem:

export A from './A';
export type { AProps } from './A';

export B from './B';
export type { BProps } from './B';

And use import * as X from './xx'. But I prefer to use import X from './xx', which means I have to export a default value from the file.

Then I create another file with code export * as default from './xx' in it and it's working well.

My question is if I can put all the export code in a single file?

CodePudding user response:

You cannot, an object cannot contain an interface. An interface is not a run-time construct that could exist in an object.

CodePudding user response:

You noted that you could use:

export A from './A';
export type { AProps } from './A';

export B from './B';
export type { BProps } from './B';

but then you'd have to use a wildcard import:

import * as X from './xx'

But did you notice that X is a namespace? Maybe you could make your own namespace... Consider the following:

import _A from './A';
import type { AProps as _AProps } from './A';

import _B from './B';
import type { BProps as _BProps } from './B';

namespace Module {
    export const A = _A;
    export const B = _B;
    export type AProps = _AProps;
    export type BProps = _BProps;
}

export default Module;

  • Related