Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c# - How to represent Guid in typescript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...