jbassking10
jbassking10

Reputation: 803

How to tell if function exists in Typescript

Given the following Javascript, how can I do the same in Typescript without getting an error?

if (typeof customizeHttpRequest === 'function') { customizeHttpRequest(xhr); }

I feel like this should be possible, or at least be able to suppress the error for this line.

Upvotes: 2

Views: 4780

Answers (3)

vesse
vesse

Reputation: 5078

Given that you might have a customizeHttpRequest function not defined anywhere in the same scope than your own code I'd assume where talking about JavaScript run in the browser? If this is the case then the function, if exists, can be found from the window object which can be patched to define these globals that appear when including a library.

declare global {
  interface Window {
    readonly customizeHttpRequest?: Function;
  }
}

if (typeof window.customizeHttpRequest === 'function') {
  window.customizeHttpRequest();
}

Upvotes: 0

jbassking10
jbassking10

Reputation: 803

Adding // @ts-ignore will ignore the following line, which in my case suppresses the error. For now, this is acceptable.

// @ts-ignore
if (typeof customizeHttpRequest === 'function') { customizeHttpRequest(xhr); }

Upvotes: 1

Ivan Dzhurov
Ivan Dzhurov

Reputation: 197

If you are sure that customizeHttpRequest will always be a function, you can simply check for its existence:

if (customizeHttpRequest) { customizeHttpRequest(xhr); }

Upvotes: 1

Related Questions