1

I am updating some old Javascript to Typescript. In Javascript you can do the following [ref]:

if (typeof functionName === "function") { 
    // safe to use the function
    functionName();
}

In Typescript this gives a syntax error "Cannot find name 'updateRadarCharts'"

I can resolve the issue with a declare statement

declare var functionName: Function;

However this doesn't feel like a clean solution because it is possible this won't be declared (hence the check). Is there a cleaner way to do this in TS ?

Zze
  • 18,229
  • 13
  • 85
  • 118

2 Answers2

4

You could declare the function as:

declare var functionName: Function | undefined;
Evert
  • 93,428
  • 18
  • 118
  • 189
1

For global augmentation (which seems to be what you are trying to achieve), a user defined type guard usually works well:

interface AugmentedGlobal {
  something: SomeType;
}

function isAugmented(obj: any): obj is AugmentedGlobal {
  return 'something' in obj;
}

if (isAugmented(global/**or window*/)) {
  const myStuff = global.something;
}