问题描述
假设我有这个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?
How to represent Guid in typescript?
推荐答案
导游通常在Javascript中用字符串表示,因此表示GUID的最简单方法是字符串。通常,当序列化为JSON时,它以字符串表示,因此使用字符串将确保与服务器中的数据兼容。
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.
使GUID与简单字符串不同,则可以使用品牌类型:
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.
这篇关于如何在打字稿中代表Guid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!