Last active
December 30, 2022 21:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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