React Props类型定义遇TS1005报错,求解决方案
问题原因及解决方法
错误根源是delete是JavaScript的保留关键字,不能用作接口属性名、变量名或组件props的参数名,这直接导致了TypeScript的语法报错。
解决步骤:
- 把props里的
delete重命名为非关键字的名称,比如onDelete或deletePost - 同步修改接口定义、组件解构参数和传递props的代码
修改后的代码示例:
1. 接口定义修改
interface AuthorPostsListProps{ posts: IPost[]; me: boolean; // 替换delete为onDelete onDelete?: () => void; }
2. 组件解构参数修改
const AuthorPostsList: FC<AuthorPostsListProps> = ({posts, me, onDelete}) => { // 后续调用函数时直接用onDelete()即可 return ( <div className='author-list'> {posts.map(post => <AuthorPostsItem me={me} key={post._id} post={post}/> )} </div> ); }; export default AuthorPostsList;
3. 传递Props的代码修改
<AuthorPostsList me={true} onDelete={deletePost} posts={posts} />
修改完成后,TypeScript的语法报错会消失,代码也符合JS/TS的语法规范。
内容的提问来源于stack exchange,提问作者stephaniex
相关产品推荐
相关产品推荐

