将多个文件中的类合并为打字稿中的单个名称空间

问题描述 投票:0回答:1

在打字稿中,我想使用其名称作为字符串来实例化一个类。我发现这可行:

const googlecommand = Object.create((Commands as any)['GoogleCommand'].prototype);

以上行与GoogleCommand位于单独的文件中。 Command必须是一个命名空间才能起作用(某些示例说默认情况下它可能会出现在window上,但对我而言并非如此),如果我只是将所有“ Command”类都放在一个文件中, namespace围绕它的命令,那会很好,因为我可以有一条import Commands from 'AllCommands'行,但是由于我想拥有许多命令,因此组织代码变得更加困难。

因此,我现在想要实现的是将每个命令放在单独的.ts文件中,然后有一个包含所有命令的单个命名空间。总而言之,这就是我想要的概念(但现在无法使用):

    // GoogleCommand.ts
    export namespace {
        export class GoogleCommand extends AbstractCommand {
            ....
        }
    }
    // BingCommand.ts
    export namespace {
        export class BingCommand extends AbstractCommand {
            ....
        }
    }
    // CommandProcessor.ts
    import { AbstractCommand } from './AbstractCommand';
    import { Commands } from './GoogleCommand';
    import { Commands } from './BingCommand';    // This will obviously conflict

    // The commandName value will come from an exteral config file so its value
    // is unknown at this point (except that it will definitely be the name of one of the commands
    let commandName;
    commandName = 'GoogleCommand';
    const googlecommand: AbstractCommand = Object.create((Commands as any)[commandName].prototype);
    commandName = 'BingCommand';
    const bingcommand: AbstractCommand = Object.create((Commands as any)[commandName].prototype);
javascript typescript
1个回答
0
投票

您将需要重命名您的类以通过它们的名称(这是您在运行时所做的事情)来专门化它们,或者在导入时为它们加上别名并编写一个映射:

// CommandProcessor.ts
import { AbstractCommand } from './AbstractCommand';
import { Commands as GoogleCommands } from './GoogleCommand';
import { Commands as BingCommands } from './BingCommand';    

const Commands = {
   GoogleCommand: GoogleCommands,
   BingCommand: BingCommands
}

// The commandName value will come from an exteral config file so its value
    // is unknown at this point (except that it will definitely be the name of one of the commands
let commandName;
commandName = 'GoogleCommand';
const googlecommand: AbstractCommand = Object.create(Commands[commandName].prototype);
commandName = 'BingCommand';
const bingcommand: AbstractCommand = Object.create(Commands[commandName].prototype);

我不确定使用名称空间的想法/好处是什么。这是TypeScript中的一个想法,Anders认为这是一个错误。

我会直接导出课程。

© www.soinside.com 2019 - 2024. All rights reserved.