Options
All
  • Public
  • Public/Protected
  • All
Menu

WHATWG URL TypeScript Interfaces

GitPitch GitHub

Provides a URL and URLSearchParams global definition that can be used in all environments. It makes it easy to have the global TypeScript definitions without having to have all of the core TypeScript browser definitions.

This makes it much simpler to write code that works in both browser and JavaScript engines. At runtime an implementation of the specification will need to be installed in the global scope.

Usage

// Expose the global URL and URLSearchParams definitions
import '@ef-carbon/url';

// Use the global URL class
const url = new URL('https://hey.there.com');

Can also use export shims for the global definitions:

// Use the global URL shim class
import { URL } from '@ef-carbon/url';

// Use the global URL class
const url = new URL('https://hey.there.com');

There are interfaces that can be used to provide strongly typed APIs:

import { IUrlImmutable, IUrlMutable, IUrlConstructible } from '@ef-carbon/url';

function immutable(endpoint: IUrlImmutable): void {
  endpoint.pathname = '/one';  // Compiler error
}

function mutable(endpoint: IUrlMutable): void {
  endpoint.pathname = '/one';  // Allowed
}

function construct(Klass: IUrlConstructible): IUrlMutable {
  return new Klass('http://wubba.lubba.com/dub/dub');
}

const url = construct(URL);
immutable(url);
mutable(url);

Installation of Classes

The global classes will need to be available when the code is actually ran. All evergreen browsers now have a URL implementation but older browsers and non-browser JavaScript engines will need an implementation installed.

Browsers

As most browsers already have a URL implementation, feature detection should be used to determine if a polyfill should be loaded. As front-end development changes rapidly it is hard to provide a concrete solution. Check the blogosphere for the current best practices.

JavaScript Engines

There is an installation helper script available to JavaScript engines:

import '@ef-carbon/url/install';

This performs the following setup:

  • Check the current global URL and URLSearchParams functionality
  • Check for a built-in WHATWG URL module with require('url') and test functionality
  • Use the fallback implementation if both fail.