TypeScript ts7053错误:用string索引table_headers对象报错如何解决?
报错原因
TypeScript 会自动推导 config.json 中 table_headers 的键为固定的字面量联合类型(当前示例中为 'appointments'),但你定义的组件Props中 headerType 是宽泛的 string 类型,TS 无法确认任意字符串一定是 table_headers 的合法键,因此抛出索引类型不匹配的错误。
解决方案
方案1:限定headerType为合法键类型(最推荐,类型安全)
直接从config对象提取table_headers的键类型作为headerType的类型约束,从根源避免非法索引:
import config from './config.json' interface TableComponentProps { // 替换原来的string类型,限定只能传table_headers中存在的键 headerType: keyof typeof config.table_headers, rows: string } export default function TableComponent(props: TableComponentProps) { // 此处不再报错,TS可正确推导header的类型 const [header] = useState(config.table_headers[props.headerType]) }
后续调用组件传入headerType时,如果传了不存在的键,TS会在编译阶段直接提示错误,避免运行时问题。
方案2:类型断言(适合临时快速验证,不建议长期使用)
如果暂时不需要严格限制headerType的取值,可以用类型断言手动告诉TS你确定当前传入的key是合法的:
const [header] = useState(config.table_headers[props.headerType as keyof typeof config.table_headers])
内容的提问来源于stack exchange,提问作者Itaru
相关产品推荐
相关产品推荐

