React类型化onChange处理函数:为何TS无法自动推断复选框类型?
为什么TypeScript无法通过
type === 'checkbox'自动推断目标元素类型? 你遇到的问题核心在于TypeScript的类型窄化逻辑无法关联解构属性与原对象的类型。
具体来说:你先从e.currentTarget(联合类型HTMLInputElement | HTMLTextAreaElement)中解构出type属性,之后判断type === 'checkbox'——但TypeScript不会跟踪这个解构出来的type变量和原对象的关联关系。它只能确定当前type的值是'checkbox',却没法反向推导得出“原对象e.currentTarget此时必然是HTMLInputElement”的结论,因此无法自动窄化原对象的类型。
两种修复方案
方案1:直接判断原对象的type属性
跳过解构步骤,直接对e.currentTarget.type做判断,TypeScript能直接关联属性与原对象的类型,完成自动窄化:
const onChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const { name } = e.currentTarget const value: string | number | boolean = e.currentTarget.type === 'checkbox' ? e.currentTarget.checked : e.currentTarget.value setState({ ...state, [name]: value }) }
方案2:将目标元素赋值给变量后再判断
把e.currentTarget存到单独变量中,TypeScript会跟踪这个变量的类型变化,通过type判断自动窄化变量类型:
const onChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const target = e.currentTarget const { name, type } = target const value: string | number | boolean = type === 'checkbox' ? target.checked : target.value setState({ ...state, [name]: value }) }
这两种方式都能让TypeScript自动完成类型推断,无需手动添加as HTMLInputElement断言。
内容的提问来源于stack exchange,提问作者André Casal
相关产品推荐
相关产品推荐

