S
S
Svyatoslav Khusamov2017-03-30 09:46:21
JavaScript
Svyatoslav Khusamov, 2017-03-30 09:46:21

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

2 answer(s)
A
Artyom Tokarevsky, 2017-03-30
@khusamov

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

K
Konstantin Kitmanov, 2017-03-30
@k12th

Well, how to mark at the input of the function that one of the function arguments will be a class?

With typeof:
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);

If you try to call useGreeter(function () {});, then TS will say that the signature does not match, PTT.
A class cannot be distinguished from a simple function in runtime, it seems to me. From a JS point of view, it's both a function. You can decorate all the necessary classes with some property - if it is, then this is a class, but this is not very elegant.
Distinguishing a class from an object is easy, the first is a function, the second is not :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question