如何让TypeScript错误提示显示类型别名userId而非number
解决TypeScript错误提示显示自定义类型别名而非原始类型的问题
要让TypeScript在错误提示里保留userId这个自定义类型别名,而非展开成它的原始类型number,你可以把userId定义为品牌类型——给原始类型附加一个唯一的品牌标识,让TypeScript将其视为独立类型,不会自动展开别名。
修改后的代码如下:
// 给number类型添加唯一品牌标识,避免TypeScript展开别名 type userId = number & { readonly __brand: unique symbol }; type PrimaryKey = `CONSUMPTION#${userId}`; export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // 此时错误提示会变为:Type '"CONSUMPTION#123a4"' is not assignable to type '`CONSUMPTION#${userId}`'.ts(2322)
原理很简单:普通类型别名(比如type userId = number)会被TypeScript当作原始类型的“别名替身”,在错误提示、类型推导时自动展开成原始类型;而带有品牌标识的交叉类型,TypeScript会将其看作一个独特的类型,从而保留别名显示。
如果需要正常使用userId类型的值,通过类型断言转换即可:
const validUserId = 123 as userId; const validPrimaryKey: PrimaryKey = `CONSUMPTION#${validUserId}`; // 不会报错
内容的提问来源于stack exchange,提问作者TheSmartMonkey
相关产品推荐
相关产品推荐

