2

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.

6
  • 2
    Typescript is just a super set of Javascript. It means that you can use that check condition in Typescript too. Commented Nov 12, 2019 at 14:30
  • what error are you getting? It looks right to me already, and that's how I test for optional callback functions. Commented Nov 12, 2019 at 14:31
  • Cannot find name "customizeHttpRequest" which makes sense since it is not declared. Commented Nov 12, 2019 at 14:51
  • @jbassking10 - you will get compile time error only in Typescript, no need to check if function exist or not. If it exist then there will no compile time error. If it is not that simple. let me know your scenario Commented Nov 12, 2019 at 16:07
  • I understand how Typescript works and how Javascript works. What I want to do is eliminate the error which I don't think is possible. The only way I could think of doing this without getting an error would be to look for the function by name - string name. However, I don't think any methods exist to do that. Commented Nov 12, 2019 at 16:45

3 Answers 3

1

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

if (customizeHttpRequest) { customizeHttpRequest(xhr); }

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I currently have an will generate an error.
Can you share the error? The approach will work, but depending on your typescript config you might have some rule not allowing you to use it. The easiest way will be to try if (customizeHttpRequest as any) { ... }
1

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); }

Comments

0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.