Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call external Javascript function from react typescript components

I have a react redux application with typescript. So the scenario is like this, I have an index.cshtml file that includes some javascript.

<script type="text/javascript">
    function test() {
        alert('Function from index.html');
    }
</script>

Now on my react component, on Main.tsx in componentWillMount() function I want to call test function.

componentWillMount() {
    window.test();
}

but this is not working for me. The message is test doesn't exist on type window

Any help is greatly appreciated.

like image 697
Rapira Avatar asked Oct 28 '25 20:10

Rapira


1 Answers

You can extend the Window interface like this:

interface Window {
    test(): void;
}

When you are doing this within a module, you need to ensure it is the global Window interface you are extending:

declare global {
    interface Window {
        test(): void;
    }
}

This provides the type implementation to the compiler.

like image 99
Fenton Avatar answered Oct 30 '25 12:10

Fenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!