构造函数参数类型

构造函数参数类型

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

问题描述

我查看了以下所有内容:

I've looked at all the following:

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

`type Constructor<T>= 功能 &{prototype: T }` 适用于 TypeScript 中的抽象构造函数类型吗?

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")
);

游乐场

这篇关于是否可以在 TypeScript 中使用 `extends` 或 `implements` 强制构造函数参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:33