let's say I have this C# class
public class Product { public Guid Id { get; set; } public string ProductName { get; set; } public Decimal Price { get; set; } public int Level { get; set; } }
The equivalent typescript would be something like:
export class Product { id: ???; productName: string; price: number; level: number; }
How to represent Guid in typescript?
Guids are usually represented as strings in Javascript, so the simplest way to represent the GUID is as a string. Usually when serialization to JSON occurs it is represented as a string, so using a string will ensure compatibility with data from the server.
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.
Unique Identifier generation is a requirement in any programming language. It contains 128 bits in size separated by a hyphen with 5 groups. Angular is an MVC framework based on Typescript. GUID and UUID generate 128 bits of the implementation.
A GUID (globally unique identifier) is a 128-bit text string that represents an identification (ID). Organizations generate GUIDs when a unique reference number is needed to identify information on a computer or network. A GUID can be used to ID hardware, software, accounts, documents and other items.
Guids are usually represented as strings in Javascript, so the simplest way to represent the GUID is as a string. Usually when serialization to JSON occurs it is represented as a string, so using a string will ensure compatibility with data from the server.
To make the GUID different from a simple string, you could use branded types:
type GUID = string & { isGuid: true}; function guid(guid: string) : GUID { return guid as GUID; // maybe add validation that the parameter is an actual guid ? } export interface Product { id: GUID; productName: string; price: number; level: number; } declare let p: Product; p.id = "" // error p.id = guid("guid data"); // ok p.id.split('-') // we have access to string methods
This article has a bit more of a discussion on branded types. Also the typescript compiler uses branded types for paths which is similar to this use case.
Another alternative is using following NPM package:
guid-typescript which you can find here: https://www.npmjs.com/package/guid-typescript
Then it will be just like this:
import { Guid } from "guid-typescript"; export class Product { id: Guid; productName: string; price: number; level: number; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With