'How to create a type in TypeScript which can be a class or a function?
I thought this could be accomplished like this:
abstract class Stuff() {
}
class Foox extends Stuff {
constructor() {
}
}
type Func = {
(a: number): number
}
let y: Func | Stuff;
y = (a = 1) => { return a }
y = Foox;
new y(); // doesn't work. This expression is not constructable. Type 'Foox' has no construct signatures
This works:
y = (a: 1) => { return a }
y = new Foox();
but this is not what I want. I want to create a value which is either a function with a specific signature or a class, not the instance of the class. How can I do this?
EDIT:
Sorry, my question wasn't entirely precise. This is what I need:
abstract class Stuff {
}
class Foox extends Stuff {
constructor() {
super();
}
}
type Func = {
(a: number): number
}
let y: Func | Foox;
y = (a = 1) => { return a }
y = Foox;
new y(); // doesn't work. This expression is not constructable. Type 'Foox' has no construct signatures
So even this doesn't work. But I don't even know the name of the subclass. All I know if that it extends the abstract class Stuff. And I would like to create type:
Function | subclass of Stuff.
EDIT 2:
Managed to make it work thanks for the suggestions guys!
let y: Func | typeof Stuff;
works. Well, kinda. I'm still getting a warning, but it's OK.
And the code that checks which type it is is just:
if(y instanceof Stuff.prototype) {
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
