'Calling "unknown" function in typescript

I am currently building a react app to integrate with OneTrust. In order to make the cookie table render dynamically, i have to call a function called OneTrust.initializeCookiePolicyHtml()

This comes from an external library and is known to the browser in the runtime. If however, I want to trigger this function from within react after mounting the component, typescript does now know how to handle this call and blocks the build.

I tried declaring Onetrust, but this only bubbles the problem further to the next property.

declare function OneTrust(any: any): any;

TS2339: Property 'initializeCookiePolicyHtml' does not exist on type '(any: any) => any'

My question here therefore is: how can I call a function that is only available through the runtime?

Thank you kindly!



Solution 1:[1]

According to your runtime code, OneTrust should be declared like this:

declare const OneTrust: {
    initializeCookiePolicyHtml: () => any;
};

OneTrust.initializeCookiePolicyHtml();

TypeScript playground

Solution 2:[2]

If you know object name at runtime yout can with code like this:

class OneTrust {
    initializeCookiePolicyHtml() {
        console.log("called initializeCookiePolicyHtml()");
    }
}
let oneTrust = new OneTrust();
const methodName = "initializeCookiePolicyHtml";
oneTrust[methodName].apply(oneTrust);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guerric P
Solution 2 user1206570