How to represent Guid in typescript?

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;
}

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.

Tags:

C#

Typescript