【发布时间】:2020-09-20 04:44:32
【问题描述】:
我必须将 React 应用程序转换为 Typescript,但我无法确定属性设置散列对象的初始状态。
原版js
export default class Wizard extends PureComponent {
constructor(props) {
super(props);
this.state = this.initialState();
}
/** Setup Steps */
initialState = () => {
const state = {
activeStep: 0,
hashKeys: {},
};
// Set initial classes
// Get hash only in client side
const hash = typeof window === 'object' ? this.getHash() : '';
const children = React.Children.toArray(this.getSteps());
children.forEach((child, i) => {
// Create hashKey map
state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`;
state.hashKeys[state.hashKeys[i]] = i;
});
...
return state;
}
...
我的失败尝试
export interface TState {
activeStep?: number
hashKeys: {
[key: number]: string
}
}
export default class StepWizard extends PureComponent<{},TState> {
constructor(props: IStepWizardProps) {
super(props)
this.state = this.initialState()
}
initialState = () => {
const state = {
activeStep: 0,
hashKeys: {}, /* <---- This seems to be the problem */
}
// Set initial classes
// Get hash only in client side
const hash = typeof window === "object" ? this.getHash() : ""
const children = React.Children.toArray(this.getSteps())
children.forEach((child, i) => {
// Create hashKey map
// the following give a TS error
// ERROR: (property) hashKeys: {}
// Element implicitly has an 'any' type because expression of type 'number'
// can't be used to index type '{}'.
// No index signature with a parameter of type 'number' was found on type '{}'.ts(7053)
state.hashKeys[i] = (child.props && child.props.hashKey) || `step${i + 1}`
state.hashKeys[state.hashKeys[i]] = i
})
...
我得到state.hasKeys[i](属性)hashKeys:{}
元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引类型“{}”。
在类型“{}”.ts(7053)
【问题讨论】:
标签: reactjs typescript