DEV Community

Jan Prazak
Jan Prazak

Posted on

6 1

randomUUID in TypeScript

How to add missing support

As of today (May 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 : "";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
brense profile image
Rense Bakker

Whats wrong with npm uuid package? npmjs.com/package/uuid It's cross-platform and they have typescript support: npm i --save-dev @types/uuid

Collapse
 
amarok24 profile image
Jan Prazak

For more advanced features sure! Thanks for the link.
My solution is for people who don't want yet another external library because the built-in Crypto API is all they need.

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!