[Solved] How to Call function as a variable in TypeScript [closed]


If you don’t want to use (), you need to make it an accessor property. (The only other way to call it without () is to use it as a tag function on a tagged template literal, which doesn’t seem relevant to what you’re doing. 🙂 )

In a class, you’d do that like this:

class Example {
    get isElementLoaded() {
        return /*...appropriate value...*/;
    }
}

In an object literal, it’s basically the same:

const obj = {
    get isElementLoaded() {
        return /*...appropriate value...*/;
    }
};

In either case, TypeScript should be able to infer the return type from your return statement, but if necessary add the annotation, e.g.:

class Example {
    get isElementLoaded(): boolean {
        return /*...appropriate value...*/;
    }
}

If you want to add an accessor to an object after it’s created, you use defineProperty:

Object.defineProperty(obj, "isElementLoaded", {
    get() {
        return /*...appropriate value...*/;
    },
    // flags here if appropriate; they default to `false` if omitted
});

You’ll need to be sure the type information for the object includes the accessor (perhaps as an optional property).

0

solved How to Call function as a variable in TypeScript [closed]