Created
February 2, 2022 13:00
-
-
Save esamattis/ca7480b878283904908c568d9f4600de to your computer and use it in GitHub Desktop.
Type-safe custom globals
This file contains hidden or 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
| function maybeGlobal<T extends object>(): Partial<T> | undefined { | |
| return (typeof window !== "undefined" ? window : undefined) as any; | |
| } | |
| maybeGlobal<{ | |
| MY_GLOBAL_VARIABLE: string; | |
| }>()?.MY_GLOBAL_VARIABLE?.toUpperCase(); |
This file contains hidden or 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
| interface MyGlobals { | |
| MY_GLOBAL_VARIABLE?: string; | |
| } | |
| type MyWindow = (Window & MyGlobals) | undefined; | |
| const myWindow: MyWindow = typeof window !== "undefined" ? window : undefined; | |
| console.log(myWindow?.MY_GLOBAL_VARIABLE?.toUpperCase() + "!"); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment