简体   繁体   English

如何将 class 类型作为参数传递?

[英]How to pass a class type as parameter?

As described here: Declare class type with TypeScript (pass class as parameter) i can pass a class type as parameter.如此处所述: 使用 TypeScript 声明 class 类型(将 class 作为参数传递)我可以将 ZA2F2ED4F2EBC2CBB4C2A 类型作为参数传递。

There is a problem这儿存在一个问题

export namespace customCommand {
    export class Command {
        public constructor(parameter?: any) {

        }
    }

    export function register(command: typeof Command) {
        new command()
    }
}

When i do this当我这样做时

customCommand.register(Map)

or或者

customCommand.register(Object)

There is no errors.没有错误。 I know that typeof Command and typeof Map both return the same result.我知道typeof Commandtypeof Map都返回相同的结果。

But how can i protect this and pass only Command type?但是我怎样才能保护它并只传递Command类型呢?

In TypeScript, you can construct a new type, something like:在 TypeScript 中,您可以构造一个新类型,例如:

type Class<T> = new (...args: any[]) => T

Which you can then use this way:然后您可以使用这种方式:

function register(command: Class<Command>) {
  new command()
}

This should constrain TypeScript to ONLY accept classes which construct or extend the Command type.这应该限制 TypeScript 只接受构造或扩展命令类型的类。

Maybe isPrototypeOf will do the trick for the classes extending the Command class:也许isPrototypeOf会为扩展Command class 的类解决问题:

export function register(command: any) {
    if (command === Command || Command.isPrototypeOf(command))
        new command()
}

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

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