打字稿中的GUID/UUID类型 [英] GUID / UUID type in typescript

查看:113
本文介绍了打字稿中的GUID/UUID类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

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

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

where id is actually GUID. Typescript doesn't have guid type. Is it possible create type GUID manually?

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

所以如果'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'会是'notGuidbutJustString',那么我会看到打字稿编译错误.

so if instead 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' will be some 'notGuidbutJustString' then I will see typescript compilation error.

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

Update: as David Sherret said: there is no way to ensure a string value based on regex or some other function at compile time but it is possible do all the checks in one place at run time.

推荐答案

您可以在字符串周围创建包装器,并将其传递给周围:

You could create a wrapper around a string and pass that around:

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

更新

另一种方法是使用品牌:

Another way of doing this is to use a brand:

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) {
}

这篇关于打字稿中的GUID/UUID类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆