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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

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!

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay