How to represent Guid in typescript?

后端 未结 3 731
Happy的楠姐
Happy的楠姐 2020-12-15 20:55

let\'s say I have this C# class

public class Product
{
   public Guid Id { get; set; }
   public string ProductName { get; set; }
   public Decimal Price { g         


        
3条回答
  •  感情败类
    2020-12-15 21:18

    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.

提交回复
热议问题