Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created June 24, 2020 11:20
Show Gist options
  • Save karol-majewski/af0c3e4fdcf6cfd9113003800ba89bc5 to your computer and use it in GitHub Desktop.
Save karol-majewski/af0c3e4fdcf6cfd9113003800ba89bc5 to your computer and use it in GitHub Desktop.
Model Window depending on the environment in TypeScript
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