Skip to content

Instantly share code, notes, and snippets.

@drumnickydrum
Last active December 30, 2022 21:12
Show Gist options
  • Save drumnickydrum/2b152cbed7b2be2a26842131c2b5b5ef to your computer and use it in GitHub Desktop.
Save drumnickydrum/2b152cbed7b2be2a26842131c2b5b5ef to your computer and use it in GitHub Desktop.
[TS: Browser Only Function] Executes fn arg only if window is in global #typescript #browser
/**
* Safely execute browser only code.
*
* @param fn - The function to execute.
* @param fallback - Optional default return value.
*
*/
function browserOnly<T>(
fn: (window: Window, document: Document) => T,
fallback?: T
): T | undefined {
if (!window || !document) {
return fallback;
}
return fn(window, document);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment