Csharp/C#教程:如何用打字稿代表Guid?分享


如何用打字稿代表Guid?

假设我有这个C#类

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

等效的打字稿类似于:

 export class Product { id: ???; productName: string; price: number; level: number; } 

如何用打字稿代表Guid?

Guids通常在Javascript中表示为字符串,因此表示GUID的最简单方式是字符串。 通常,当序列化为JSON时,它表示为字符串,因此使用字符串将确保与来自服务器的数据兼容。

要使GUID与简单字符串不同,您可以使用品牌类型:

 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 

本文对品牌类型进行了更多讨论。 typescript编译器也使用类似于此用例的路径的品牌类型。

上述就是C#学习教程:如何用打字稿代表Guid?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1002179.html

(0)
上一篇 2021年12月28日
下一篇 2021年12月28日

精彩推荐