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 : "";
}
Top comments (2)
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
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.