Answer the question
In order to leave comments, you need to log in
How to distinguish a class from an object or a simple function in Typescript?
How to distinguish a class from an object or a simple function in Typescript?
Any typeof and instanceof do not help here.
And I need to know what I got at the input - a class or its instance.
Well, how to mark at the input of the function that one of the function arguments will be a class?
Answer the question
In order to leave comments, you need to log in
What does "one of the function arguments will be a class" mean? It will still be a function, but representing a certain class in the program structure. Well, of course, you can receive as an argument either a function that will create an object for us, or an already created object. But why? Somehow the purpose is not very clear.
And you can mark with interfaces, here is an example from the documentation:
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
Well, how to mark at the input of the function that one of the function arguments will be a class?
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
function useGreeter(cls: typeof Greeter): Greeter {
return new cls("world");
}
useGreeter(Greeter);
useGreeter(function () {});
, then TS will say that the signature does not match, PTT. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question