After conducting thorough research, I have reviewed the following resources:
Abstract constructor type in TypeScript
How does `type Constructor<T> = Function & { prototype: T }` apply to Abstract constructor types in TypeScript?
Abstract Constructor on Abstract Class in TypeScript
Out of these, the third resource seemed closest to addressing my query, but unfortunately, the answer focused more on a specific issue rather than the overarching question.
To provide some context, here is an example of what I aim to achieve:
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")
);
In this demonstration, both Shouter and NamedCat require only one string argument for their constructors. While they could potentially implement an interface instead of extending a class, my goal is to compile a list of classes that necessitate identical arguments for instantiation.
My primary inquiry pertains to whether it is feasible to enforce a class's constructor parameter types using extends
or implements
in TypeScript.
EDIT: The "Possible Duplicate" reference indicates the limitations of utilizing new()
within an interface for this purpose. Consequently, I am exploring alternative methodologies to address this challenge.