是否可以在TypeScript中使用`extends`或`implements`来强制执行构造函数参数类型? [英] Is it possible to enforce constructor parameter types with `extends` or `implements` in TypeScript?

查看:448
本文介绍了是否可以在TypeScript中使用`extends`或`implements`来强制执行构造函数参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了以下所有内容:

I've looked at all the following:

  1. TypeScript中的抽象构造函数类型

如何键入"Constructor< T>"类型=功能& {prototype:T}`是否适用于TypeScript中的Abstract构造函数类型?

TypeScript中抽象类的抽象构造方法

第三个是最接近我要查找的内容,但是(不幸的是)答案更多地是针对特定问题的,而问题标题的却较少.

The third is the closest to what I'm looking for, but (unfortunately) the answer was more for the specific issue and less for the question title.

(从简单的意义上来说)这是我想做的事情:

This is (in a simplified sense) what I'd like to be able to do:

abstract class HasStringAsOnlyConstructorArg {
  abstract constructor(str: string);
}

class NamedCat extends HasStringAsOnlyConstructorArg {
  constructor(name: string) { console.log(`meow I'm ${name}`); }
}

class Shouter extends HasStringAsOnlyConstructorArg {
  constructor(phrase: string) { console.log(`${phrase}!!!!!!`); }
}

const creatableClasses: Array<typeof HasStringAsOnlyConstructorArg> = [NamedCat, Shouter];
creatableClasses.forEach(
  (class: typeof HasStringAsOnlyConstructorArg) => new class("Sprinkles")
);

在上面的示例中,您可以看到Shouter和NamedCat都使用一个字符串作为其构造函数.他们不一定需要扩展一个类,他们可以实现一个接口或其他东西,但是我确实希望能够保存一列需要完全相同的参数来构造的类.

In the example above you can see that Shouter and NamedCat both use one single string for their constructor. They don't necessarily need to extend a class, they could implement an interface or something, but I really want to be able to hold a list of classes that require the exact same arguments to construct.

是否可以在TypeScript中使用extendsimplements强制执行类构造函数参数类型?

Is it possible to enforce a classes constructor parameter types with extends or implements in TypeScript?

出现可能重复"以显示如何无法在接口中为此目的使用new().也许还有其他方法.

The "Possible Duplicate" appears to show how it is not possible to use new() in an interface for this purpose. Perhaps there are still other ways.

推荐答案

您可以对数组本身进行这种强制执行,因此它将仅允许带有单个字符串参数的构造函数:

You can do such enforcement on array itself, so it will allow only constructors with single string argument:

class NamedCat {
    constructor(name: string) { console.log(`meow I'm ${name}`); }
}

class Shouter {
    constructor(phrase: string) { console.log(`${phrase}!!!!!!`); }
}

type ConstructorWithSingleStringArg = new (args: string) => any;

const creatableClasses: Array<ConstructorWithSingleStringArg> = [NamedCat, Shouter];
creatableClasses.forEach(
    ctor => new ctor("Sprinkles")
);

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆