如何用打字稿代表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编译器也使用类似于此用例的路径的品牌类型。