将手机号格式化JS代码转为TS时的事件对象类型错误问题
TypeScript中事件对象的正确类型写法
你的代码报错是因为原JS里把event定义为宽泛的object类型,TypeScript需要更精确的类型来做类型检查,避免属性访问错误。以下是两种常见场景下的修正方案:
1. React项目场景
如果是在React项目中使用该事件处理函数,直接给event指定React.ChangeEvent<HTMLInputElement>类型即可,这个类型会自动识别event.target为输入框元素:
/** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value: string): string => { const areaCode = value.substr(0, 3); const prefix = value.substr(3, 3); const suffix = value.substr(6, 4); const output = `(${areaCode}) ${prefix}-${suffix}`; return output; }; /** * Event handler for a phone number input to update the phone number's formatting * @param {React.ChangeEvent<HTMLInputElement>} event Input change event object */ export const formatPhoneNumber = (event: React.ChangeEvent<HTMLInputElement>) => { const targetElement = event.target; // Get the value and remove all of the non-digit characters const value = targetElement.value.replace(/\D/g, ''); if (value.length === 10) { const output = formatPhoneString(value); // Update the value of the input targetElement.value = output; } };
2. 原生TypeScript(浏览器)场景
如果是原生浏览器环境下的TypeScript代码,可以使用InputEvent类型,并通过类型断言把event.target指定为HTMLInputElement(明确事件来自输入框):
/** * @param {string} value The value to be formatted into a phone number * @returns {string} */ export const formatPhoneString = (value: string): string => { const areaCode = value.substr(0, 3); const prefix = value.substr(3, 3); const suffix = value.substr(6, 4); const output = `(${areaCode}) ${prefix}-${suffix}`; return output; }; /** * Event handler for a phone number input to update the phone number's formatting * @param {InputEvent} event Input event object */ export const formatPhoneNumber = (event: InputEvent) => { // 断言target为HTMLInputElement,确保TypeScript识别value属性 const targetElement = event.target as HTMLInputElement; // Get the value and remove all of the non-digit characters const value = targetElement.value.replace(/\D/g, ''); if (value.length === 10) { const output = formatPhoneString(value); // Update the value of the input targetElement.value = output; } };
另外,给formatPhoneString函数补充了参数和返回值的类型注解,这是TypeScript的规范写法,能进一步规避类型错误。
内容的提问来源于stack exchange,提问作者MRF88
相关产品推荐
相关产品推荐

