TypeScript中如何为customCell的message、info参数添加类型?解决报错
解决TypeScript解构参数类型标注错误的问题
你报错的核心原因是:你写的{message: any, info: any}是把解构出来的变量重命名为any,而非给message和info指定类型——这会导致重复声明any变量,同时原变量message、info未被定义,因此触发报错。
以下是两种正确的写法:
方法1:直接在解构参数上标注类型
如果只是单次使用,可直接在解构的参数对象后标注类型:
const input = [ { id: 'id', name: 'description', // 这里给第二个参数的对象标注类型,解构出的message/info自动继承类型 customCell: (_: any, { message, info }: { message?: string; info?: string }) => message ? message : info, }, ]
注:示例中用string和可选符号?是假设类型,你可以根据实际业务改成number、boolean或必填类型(去掉?)。
方法2:提前定义接口复用类型
如果这个参数类型会被多处使用,建议先定义接口:
// 定义参数接口,统一管理类型 interface CustomCellParams { message?: string; info?: string; } const input = [ { id: 'id', name: 'description', customCell: (_: any, { message, info }: CustomCellParams) => message ? message : info, }, ]
内容的提问来源于stack exchange,提问作者stackuser
相关产品推荐
相关产品推荐

