首页 > 解决方案 > 如何为 TypeScript React 应用程序设置键/值默认状态

问题描述

我必须将 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
    })

   ...

我得到 for state.hasKeys[i](property) hashKeys: {} Element 隐式具有“any”类型,因为“number”类型的表达式不能用于索引类型“{}”。在类型 '{}'.ts(7053) 上找不到具有类型参数的索引签名

标签: reactjstypescript

解决方案


问题似乎来自 hashKeys 的定义为{}.

Typescript 不知道键/值的数据类型,但是,你可以告诉它!

const hashKeys = {} as Record<number, string>;

const x = hashKeys[0];

对于您的示例:

        const state = {
            activeStep: 0,
            hashKeys: {} as Record<string, string>, // or whatever your types are
        };

推荐阅读