Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GUID / UUID type in typescript

I have this function:

function getProduct(id: string){    
    //return some product 
}

where id is actually GUID. Typescript doesn't have guid type. Is it possible create type GUID manually?

function getProduct(id: GUID){    
    //return some product 
}

so if instead 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' will be some 'notGuidbutJustString' then I will see typescript compilation error.

Update: as David Sherret said: there is no way to ensure a string value based on regex or some other function at compile time but it is possible do all the checks in one place at run time.

like image 868
Rajab Shakirov Avatar asked May 10 '16 16:05

Rajab Shakirov


People also ask

Does TypeScript have GUID?

Although neither the TypeScript nor JavaScript language have built-in support for generating a UUID or GUID, there are plenty of quality 3rd party, open-source libraries that you can use.

Is GUID same as UUID?

The GUID designation is an industry standard defined by Microsoft to provide a reference number which is unique in any context. UUID is a term that stands for Universal Unique Identifier. Similarly, GUID stands for Globally Unique Identifier. So basically, two terms for the same thing.

What is types UUID?

The data type uuid stores Universally Unique Identifiers (UUID) as defined by RFC 4122, ISO/IEC 9834-8:2005, and related standards. (Some systems refer to this data type as a globally unique identifier, or GUID, instead.)


2 Answers

You could create a wrapper around a string and pass that around:

class GUID {     private str: string;      constructor(str?: string) {         this.str = str || GUID.getNewGUIDString();     }      toString() {         return this.str;     }      private static getNewGUIDString() {         // your favourite guid generation function could go here         // ex: http://stackoverflow.com/a/8809472/188246         let d = new Date().getTime();         if (window.performance && typeof window.performance.now === "function") {             d += performance.now(); //use high-precision timer if available         }         return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {             let r = (d + Math.random() * 16) % 16 | 0;             d = Math.floor(d/16);             return (c=='x' ? r : (r & 0x3 | 0x8)).toString(16);         });     } }  function getProduct(id: GUID) {         alert(id); // alerts "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx" }  const guid = new GUID("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"); getProduct(guid); // ok getProduct("notGuidbutJustString"); // errors, good  const guid2 = new GUID(); console.log(guid2.toString()); // some guid string 

Update

Another way of doing this is to use a brand:

type Guid = string & { _guidBrand: undefined };  function makeGuid(text: string): Guid {   // todo: add some validation and normalization here   return text as Guid; }  const someValue = "someString"; const myGuid = makeGuid("ef3c1860-5ce6-47af-a13d-1ed72f65b641");  expectsGuid(someValue); // error, good expectsGuid(myGuid); // ok, good  function expectsGuid(guid: Guid) { } 
like image 55
David Sherret Avatar answered Sep 21 '22 23:09

David Sherret


I think one should extend a bit on the answer by David Sherret.
Like this:

// export  class InvalidUuidError extends Error {     constructor(m?: string) {         super(m || "Error: invalid UUID !");          // Set the prototype explicitly.         Object.setPrototypeOf(this, InvalidUuidError.prototype);     }  }   // export  class UUID  {     protected m_str: string;      constructor(str?: string) {         this.m_str = str || UUID.newUuid().toString();          let reg:RegExp = new RegExp("[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}", "i")         if(!reg.test(this.m_str))             throw new InvalidUuidError();     }      toString() {         return this.m_str;     }      public static newUuid(version?:number) :UUID     {         version = version || 4;           // your favourite guid generation function could go here         // ex: http://stackoverflow.com/a/8809472/188246         let d = new Date().getTime();         if (window.performance && typeof window.performance.now === "function") {             d += performance.now(); //use high-precision timer if available         }         let uuid:string = ('xxxxxxxx-xxxx-' + version.toString().substr(0,1) + 'xxx-yxxx-xxxxxxxxxxxx').replace(/[xy]/g, (c) => {             let r = (d + Math.random() * 16) % 16 | 0;             d = Math.floor(d/16);             return (c=='x' ? r : (r & 0x3 | 0x8)).toString(16);         });          return new UUID(uuid);     } }   function getProduct(id: UUID) {         alert(id); // alerts "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx" }   const guid2 = new UUID(); console.log(guid2.toString()); // some guid string   const guid = new UUID("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"); getProduct(guid); // ok getProduct("notGuidbutJustString"); // errors, good 
like image 30
Stefan Steiger Avatar answered Sep 21 '22 23:09

Stefan Steiger