import React, { Component } from 'react';
import './App.css';
interface IProps {
[propName: string]: any;
}
interface IState {
statusKey: IStatusKey;
}
// 定义key值的类型
type IStatusKey = "open" | "over";
export default class App extends Component<IProps, IState> {
constructor(props: IProps) {
super(props)
this.state = {
// 假设这个key值是后端返回的,需要映射到statusMap中
statusKey: "open",
}
}
// 定义需要映射的数据(模拟)
private statusMap = {
open: {
name: "11",
age: 10
},
over: {
name: "22",
age: 20
}
}
componentDidMount = () => {
// 直接使用就不报错了
const m2Date = this.statusMap[this.state.statusKey];
console.log("m2", m2Date)
}
render() {
return (
<div className='view'>测试</div>
)
}
}
解决typescript报错:“元素隐式具有 “any“ 类型,因为类型为 “string“ 的表达式不能用于索引类型”
最新推荐文章于 2024-04-22 23:18:29 发布