简体   繁体   中英

Multiple exports with dot notation in Typescript

Ref. this question .

I'm trying to do exactly the same, but with Typescript.

Problem

This line (just before the export statement):

Sidebar.Item = SidebarItem;

gives compile error: Property 'Item' does not exist on type 'typeof Sidebar'

Attempted solution 1

I've tried adding Item to my Sidebar class definition, like so:

class Sidebar extends Component<SidebarProps, SidebarState> {
    Item: SidebarItem;
    ...
}

But that results in this error: Public property 'Item' of exported class has or is using private name 'SidebarItem'.

Attempted solution 2

I've tried removing this line:

Sidebar.Item = SidebarItem;

And instead of adding Item to my class definition, I'm exporting both classes like so:

export default Sidebar;
export { SidebarItem as Item };

Which does compile, and I am able to import everything like so:

import * as Sidebar from '...';

But then I have to use them like so:

<Sidebar.default>
    <Sidebar.Item></Sidebar.Item>
    <Sidebar.Item></Sidebar.Item>
</Sidebar.default>

And I really want to get rid of that .default in Sidebar .

What am I doing wrong here?

This module is faulty by design.

It likely can be done with:

export class SidebarItem ...

export default class Sidebar extends Component<SidebarProps, SidebarState> {
    static Item = SidebarItem;
    ...
}

And there is no good reason why these two components should maintain a hierarchy like that.

It's conventional to have CamelCased components and use separate named exports if there's more than one export of equal value (which components are). Named exports are better for auto-import in IDEs:

export { Sidebar, SidebarItem };

Item cannot be tree-shaken from default export when needed. Sidebar.Item minifies less efficiently than SidebarItem .

Your first solution is almost correct, but you declare Item as a property on objects of the Sidebar class, rather than on the class itself. You can do the latter with a static property declaration. This should work:

export class SidebarItem ..
..
class Sidebar extends Component<SidebarProps, SidebarState> {
  static Item = SidebarItem;
..
export default Sidebar;

You won't need the line Sidebar.Item = SidebarItem; anymore, but you might need to move the SidebarItem class so it appears before Sidebar . The import will just be import Sidebar from '...' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM