randomUUID in TypeScript

randomUUID in TypeScript

How to add missing support

As of today (Feb 2022) TypeScript type definition files lack Crypto API's randomUUID method.

I came up with this short solution which doesn't require modifying the typedef files. It is a simple workaround which exports the randomUUID method as generateUUID, and also checks browser support (returns an empty string if not supported in your browser). Maybe it will be of some use to others until TS gets updated.

More about randomUUID on MDN here. Overview of browser support here

export {generateUUID};

interface CryptoNew extends Crypto
{
  randomUUID?(): string;
}

// Returns an empty string if Crypto API or randomUUID is not supported by browser.
function generateUUID(): string
{
  let cryptoRef: CryptoNew;
  let r: string | undefined = '';

  if (typeof self.crypto !== 'undefined')
  {
    cryptoRef = self.crypto;
    r = cryptoRef.randomUUID?.();
  }

  return r ? r : '';
}