如何在打字稿中代表Guid?

Ric*_*d77 6 c# typescript

假设我有这个C#类别

public class Product
{
   public Guid Id { get; set; }
   public string ProductName { get; set; }
   public Decimal Price { get; set; }
   public int Level { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

等效的打字稿如下所示:

export class Product {
  id: ???;
  productName: string;
  price: number;
  level: number;
}
Run Code Online (Sandbox Code Playgroud)

如何在打字稿中代表Guid?

Jag*_*ngh 14

另一种选择是使用以下 NPM 包:

guid-typescript,你可以在这里找到:https : //www.npmjs.com/package/guid-typescript

然后它会是这样的:

import { Guid } from "guid-typescript";

export class Product {
    id: Guid;
    productName: string;
    price: number;
    level: number;
}
Run Code Online (Sandbox Code Playgroud)


Tit*_*mir 7

向导通常用Java脚本中的字符串表示,因此表示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
Run Code Online (Sandbox Code Playgroud)

文章中有更多关于品牌类型的讨论的一个位。打字稿编译器也使用品牌类型的路径,类似于此用例。