简体   繁体   English

如何在TypeScript中使用静态嵌套类导出类?

[英]How to export class with static nested class in TypeScript?

In order to create nested static class i follow this 为了创建嵌套的静态类,我遵循以下步骤

class Album {
    label: Album.AlbumLabel;
}
namespace Album {
    export class AlbumLabel { }
}

However, I need to export class Album too. 但是,我也需要导出类Album。 When I do 当我做

export class Album {
    label: Album.AlbumLabel;
}
namespace Album {
    export class AlbumLabel { }
}

I get Individuals declarations in merged declaration 'Album' must be all exported or all local . 我得到Individuals declarations in merged declaration 'Album' must be all exported or all local How to fix it? 如何解决?

Option one is to do as your told by the compiler and export both: 方法一是按照编译器的指示进行操作,然后导出两者:

export class Album {
    label: Album.AlbumLabel;
}

export namespace Album {
    export class AlbumLabel { }
}

Option two is a shimmy variable, but you have a naming dilemma: 选项二是一个有误差的变量,但是您有一个命名难题:

class Album {
    label: Album.AlbumLabel;
}

namespace Album {
    export class AlbumLabel { }
}

export const NameMe = Album;

The first option is a better choice (I reckon). 第一种选择是更好的选择(我认为)。

Imports 进口

If you want to import AlbumLabel directly, don't nest it. 如果要直接导入AlbumLabel ,请不要嵌套它。 It's in a module already, so have the module export Album and AlbumLabel . 它已经在一个模块中,因此该模块可以导出AlbumAlbumLabel

If you keep the nesting you have to use either: 如果保留嵌套,则必须使用以下任一方法:

import { Album } from './component.js';

const a = new Album.AlbumLabel();

Or introduce a local name: 或引入一个本地名称:

import { Album } from './component.js';
const AlbumLabel = Album.AlbumLabel;

const a = new AlbumLabel();

Here's the example that allows import { AlbumLabel } from './album'; 这是允许import { AlbumLabel } from './album';

export class Album {
    label: AlbumLabel;
}

export class AlbumLabel { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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