我在我的应用中有多种类型的整数ID(例如ProductId,UserId等),我想实现强类型化,以便可以确保将正确的ID类型传递给方法。
例如我想声明GetProduct(productId: ProductId)
而不是GetProduct(productId: number)
,以便只能将ProductId类型的变量传递给它。
在我的C天中,我将使用typedef-例如typedef ProductId int;
在C#中,我通过定义一个ProductId类来实现这一点,该类具有对int运算符的隐式转换和对int运算符的显式转换。比typedef麻烦,但它可以工作。
我正在尝试找出如何完成Typescript中的等效操作。对于TypeScript,我尝试了此操作:
export class ProductId extends Number {}
但是这仍然允许使用数字代替ProductId。
如何在TypeScript中完成此操作?
Type别名在打字稿中可用。
export type ProductId = number;