JS/TS数值格式化函数:如何捕获无效key传入的错误?
TypeScript数值格式化函数问题解答
一、捕获无效numType的错误
原函数中,如果传入的numType不在numTypeMap的键列表里,numTypeMap[numType]会返回undefined,调用undefined()会直接触发运行时错误。要提前捕获这个问题,可以在调用格式化函数前先检查是否存在对应的函数:
修改后的代码示例
export const getFormattedValue = ( value: number | null | undefined, numType: string, options?: { round?: boolean; expanded?: boolean } ): string => { if (value === null || value === undefined) { return ''; } const numTypeMap: { [t: string]: (n: number, round?: boolean, expanded?: boolean) => string } = { number: toReadableNumber, percent: toReadablePercentage, dollar: toReadableDollar, canadianDollar: toReadableCanadianDollar, pound: toReadablePound, euro: toReadableEuro, }; // 取出对应格式化函数 const formatter = numTypeMap[numType]; // 检查函数是否存在,不存在则抛出明确错误 if (!formatter) { throw new Error(`无效的numType:${numType},可选值为:${Object.keys(numTypeMap).join(', ')}`); // 若不想抛出错误,也可以返回默认提示文本,比如: // return `[无效类型:${numType}]`; } return formatter(value, options?.round, options?.expanded); };
这样一来,当传入无效值时,会抛出包含可选值列表的错误,方便排查问题;如果业务不需要抛出错误,返回自定义提示文本也可以。
二、获取numTypeMap的键
要获取对象的所有键,直接用Object.keys()方法即可,它会返回一个包含对象所有可枚举字符串键的数组:
示例代码
// 假设numTypeMap已定义 const validNumTypes = Object.keys(numTypeMap); console.log(validNumTypes); // 输出:["number", "percent", "dollar", "canadianDollar", "pound", "euro"]
进阶:TypeScript编译时校验
如果想在编译阶段就阻止传入无效的numType,可以把numType的类型从string改为keyof typeof numTypeMap,这样TypeScript会自动把参数限制为numTypeMap的合法键:
export const getFormattedValue = ( value: number | null | undefined, numType: keyof typeof numTypeMap, // 修改类型 options?: { round?: boolean; expanded?: boolean } ): string => { // ... 其余代码不变 };
此时如果传入"invalidType"这类无效值,TypeScript在编译时就会报错,提前避免运行时问题。
内容的提问来源于stack exchange,提问作者Slacker101
相关产品推荐
相关产品推荐

