types - typescript 中的 GUID/UUID 类型

标签 types typescript guid uuid

我有这个功能:

function getProduct(id: string){    
    //return some product 
}

其中 id 实际上是 GUID。 Typescript 没有 guid 类型。是否可以手动创建类型 GUID

function getProduct(id: GUID){    
    //return some product 
}

所以如果 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' 将是一些 'notGuidbutJustString' 那么我将看到 typescript 编译错误。

更新:正如 David Sherret 所说:无法在编译时确保基于正则表达式或其他一些函数的字符串值,但可以在运行时在一个地方进行所有检查.

最佳答案

您可以围绕一个字符串创建一个包装器并将其传递:

class GUID {
    private str: string;

    constructor(str?: string) {
        this.str = str || GUID.getNewGUIDString();
    }

    toString() {
        return this.str;
    }

    private static getNewGUIDString() {
        // your favourite guid generation function could go here
        // ex: http://stackoverflow.com/a/8809472/188246
        let d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            let r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d/16);
            return (c=='x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }
}

function getProduct(id: GUID) {    
    alert(id); // alerts "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
}

const guid = new GUID("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx");
getProduct(guid); // ok
getProduct("notGuidbutJustString"); // errors, good

const guid2 = new GUID();
console.log(guid2.toString()); // some guid string

更新

另一种方法是使用品牌:

type Guid = string & { _guidBrand: undefined };

function makeGuid(text: string): Guid {
  // todo: add some validation and normalization here
  return text as Guid;
}

const someValue = "someString";
const myGuid = makeGuid("ef3c1860-5ce6-47af-a13d-1ed72f65b641");

expectsGuid(someValue); // error, good
expectsGuid(myGuid); // ok, good

function expectsGuid(guid: Guid) {
}

关于types - typescript 中的 GUID/UUID 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37144672/

相关文章:

javascript - 基于js中种子字符串的相同uuid

c# - 具有始终相等编号的 GUID

c# - 什么是(<类型>?)?

scala - 路径相关类型是类型投影吗?

python - 将空类型从 XLS 行转换为字符串

angular - "TypeError: Cannot read property ' 在 ngrx 商店中发布 ' of undefined",仅在生产版本中具有 Angular

c# - 在 C#/WPF 中确定控件类型的最有效方法

javascript - sinon.js 监视 $.dataTables 函数

typescript - 如何使用 Angular 2 管道对对象列表进行排序

c# - GUID 是否及时订购?如果 ORDER BY 与 GUID 变量类型一起使用,最近创建的记录是否会延迟?