Created
June 24, 2020 11:20
-
-
Save karol-majewski/af0c3e4fdcf6cfd9113003800ba89bc5 to your computer and use it in GitHub Desktop.
Model Window depending on the environment in TypeScript
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
enum Hostname { | |
IPv4 = 'localhost', | |
IPv4Default = '127.0.0.0/8', | |
IPv6 = '[::1]', | |
} | |
const isLocalhost = (window: Window): window is Window.Localhost => ( | |
window.location.hostname === 'localhost' || | |
window.location.hostname === '[::1]' || | |
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/.test(window.location.hostname) | |
) | |
declare namespace Window { | |
interface Localhost extends Window { | |
location: Window['location'] & { hostname: Hostname }; | |
__DEVTOOLS__: boolean; | |
} | |
} | |
function assert(condition: boolean): asserts condition { | |
if (!condition) { | |
throw new Error() | |
} | |
} | |
/** | |
* If you expect this module to be executed ONLY in development | |
*/ | |
assert(isLocalhost(window)); | |
window.__DEVTOOLS__; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment