How to call Javascript functions in React Typescript

Last updated : November 13, 2022

Sometimes we have to use third-party Javascript libraries with React Js Typescript applications. That's because those external files may be too large to convert to Typescript, or we don't have access to alter them. In this tutorial, I will show you how to call functions hosted in an external Javascript file.

The main problem I encounter is type check errors from Typescript because Typescript is unaware of the function name that I want to call. Again, that's because the function is external and written in Javascript.

Here is my external Javascript file. It has a few functions and an object.

function highlightSyntax(){
    console.log("Syntax highlighted")
}

var externalObject = {
    enhanceImages :function enhanceImages(){
        console.log("Enhancing images")
    },
    measureTimeOnPage :function measureTimeOnPage(){
        console.log("Measuring time on page")
    }
}

I can link to this Javascript file in my index.html file.

<script type='text/javascript' src='/path/some_external_javascript.js' ></script>

That will load my Javascript file with the React application. Also, my functions become available to execute globally. But Typescript is still unaware of them. This is what happens when I try to call those functions in Typescript.

External Javascript error in React Typescript
Figure 1 : External Javascript error in React Typescript

Follow the below steps to call external Javascript functions with React Typescript.

1. Create a global.d.ts file.

I place my global.d.ts in the app root directory.

2. Insert the type definitions to match the external function and object names.

Since my external resources are available through the browser's window object, I must override the Window interface and define the new properties there.

interface Window {
    highlightSyntax: () => void
    externalObject: {
        enhanceImages: () => void,
        measureTimeOnPage: () => void
    }
}

3. Access the functions through optional chaining.

Now I can access my external functions through Typescript without any errors. But I must use optional chaining to avoid any null references due to loading delays.

const App = () => {

const callJavascript = () => {
  window?.highlightSyntax?.()
}
const callOtherJavascript = () => {
  window?.externalObject?.measureTimeOnPage?.()
  window?.externalObject?.enhanceImages?.()
}
  return (
    <div>
      <button onClick={callJavascript}>Call Javascript Function</button>
      <button onClick={callOtherJavascript}>Call Other external JS</button>
    </div>
  );
}
export default App;
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments