面试题答案
一键面试在TypeScript中可以通过接口或类型别名来实现名义类型。以下是使用类型别名的示例:
// 定义UserId类型别名
type UserId = { __brand: 'UserId' } & number;
// 定义ProductId类型别名
type ProductId = { __brand: 'ProductId' } & number;
// 创建UserId实例
const userId: UserId = 1 as UserId;
// 创建ProductId实例
const productId: ProductId = 2 as ProductId;
// 以下代码会报错,因为明确区分了UserId和ProductId
// const wrongAssignment: UserId = productId;
这里通过在类型别名中添加一个独一无二的 __brand
属性来在名义上区分 UserId
和 ProductId
,虽然它们本质上还是 number
类型,但TypeScript 会根据这个额外的属性来区分它们。