Categories
TypeScript Answers

How to create the GUID class with TypeScript?

Spread the love

Sometimes, we want to create the GUID class with TypeScript.

In this article, we’ll look at how to create the GUID class with TypeScript.

How to create the GUID class with TypeScript?

To create the GUID class with TypeScript, we can create a class and add a static method that returns GUID into it.

For instance, we write

class Guid {
  static newGuid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
      const r = (Math.random() * 16) | 0;
      const v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }
}

to create the Guid class with the newGuid static method.

In it, we have the placeholder string "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx" and we call replace on it to replace the placeholders x and y with random values.

We use the bitwise & operator to replace any values that aren’t x.

Then we return the hex string with v.toString(16).

Conclusion

To create the GUID class with TypeScript, we can create a class and add a static method that returns GUID into it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *