我有这个功能:

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编译错误.

Update:正如David Sherret所说:没有办法确保编译时基于regex或其他函数的字符串值,但有可能在运行时在一个地方执行所有判断.

推荐答案

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

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

Update

另一种方法是使用品牌:

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

Typescript相关问答推荐

我可以让Typescript根据已区分的联合键缩小对象值类型吗?

带有联合参数的静态大小数组

在配置对象上映射时,类型脚本不正确地推断函数参数

如何将联合文字类型限制为文字类型之一

在键和值为ARGS的泛型函数中未正确推断类型

打字脚本中泛型和直接类型重新映射的不同行为

如何根据特定操作隐藏按钮

我可以使用TypeScrip从字符串词典/记录中填充强类型的环境对象吗?

Angular文件上传到Spring Boot失败,多部分边界拒绝

使用2个派生类作为WeakMap的键

寻址对象中路径的泛型类型

使用条件类型的类型保护

如何从一个泛型类型推断多个类型

类型与泛型抽象类中的类型不可比较

如何在不违反挂钩规则的情况下动态更改显示内容(带有状态)?

无法缩小深度嵌套对象props 的范围

使用RXJS获取数据的3种不同REST API

在Vite中将SVG导入为ReactComponent-不明确的间接导出:ReactComponent

Typescript 和 Rust 中跨平台的位移数字不一致

我应该使用服务方法(依赖于可观察的)在组件中进行计算吗?