打字稿中的GUID/UUID类型

Raj*_*rov 11 uuid types guid typescript

我有这个功能:

function getProduct(id: string){    
    //return some product 
}
Run Code Online (Sandbox Code Playgroud)

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

function getProduct(id: GUID){    
    //return some product 
}
Run Code Online (Sandbox Code Playgroud)

所以,如果反而'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'会有些'notGuidbutJustString'话,我会看到打字稿编译错误.

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

Dav*_*ret 17

您可以在字符串周围创建一个包装器并传递它:

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
Run Code Online (Sandbox Code Playgroud)

  • 但是这个包装器在其他地方移动我的问题,因为我仍然可以这样做:const guid = new GUID("notGuidbutJustString").当然我可以在GUID类中添加一些运行时检查,但我希望在应用程序启动之前看到错误... (3认同)
  • @Rajab在编译时无法确保基于正则表达式或其他函数的字符串值.我建议使用书面单元测试来解决这个问题. (3认同)