Typedef等同于打字稿

问题描述 投票:0回答:1

我在我的应用中有多种类型的整数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中完成此操作?

typescript typedef
1个回答
0
投票

Type别名在打字稿中可用。

export type ProductId = number;

© www.soinside.com 2019 - 2024. All rights reserved.