使用自定义Hook时出现TypeScript错误:Property does not exist on type
问题描述
我声明了一个自定义Hook,代码如下:
type ControlContextProps = | { name: string | undefined; id: string | undefined; selectedOptions: String[] | undefined; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; } | {}; const FormControlContext = React.createContext<ControlContextProps>({}); const useFormControl = () => { const context = React.useContext(FormControlContext); return context; };
在使用该Hook时,解构ControlContextProps中定义的字段(如id、name等)会触发TypeScript错误:Property 'xxx' does not exist on type 'ControlContextProps'.ts(2339),所有字段均会出现该错误。
使用代码示例:
const { id, name, selectedOptions, onChange } = useFormControl();
原因及解决方法
问题出在ControlContextProps的联合类型定义上:你将包含完整字段的对象与空对象{}做了联合,TypeScript判定ControlContextProps的实例可能是空对象,而空对象不存在id、name等属性,因此解构时会触发类型错误。
以下是两种可行的修复方案:
方案一:将所有字段设为可选(推荐)
把联合类型改为单对象类型,给所有字段添加可选标记?,既保留“字段可能不存在”的语义,又能让TypeScript识别到这些字段的存在:
type ControlContextProps = { name?: string; id?: string; selectedOptions?: string[]; // 注意:优先使用小写string,避免大写包装类型String onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void; }; const FormControlContext = React.createContext<ControlContextProps>({}); const useFormControl = () => { const context = React.useContext(FormControlContext); return context; };
方案二:提供完整的上下文默认值
如果业务逻辑要求上下文必须包含所有字段(允许值为undefined),可以给上下文提供完整的默认值,同时调整类型为非联合的完整对象:
type ControlContextProps = { name: string | undefined; id: string | undefined; selectedOptions: string[] | undefined; onChange: (e: React.ChangeEvent<HTMLInputElement>) => void; }; // 提供包含所有字段的默认值,包括onChange的空函数实现 const FormControlContext = React.createContext<ControlContextProps>({ name: undefined, id: undefined, selectedOptions: undefined, onChange: () => {}, }); const useFormControl = () => { const context = React.useContext(FormControlContext); return context; };
内容的提问来源于stack exchange,提问作者mfreitas
相关产品推荐
相关产品推荐

