Typescript中带有对象数组的接口的麻烦

时间:2018-10-04 20:41:35

标签: reactjs typescript

我有一个数组,它是我在componentDidMount生命周期挂钩中填充的状态条目,它很简单:

state{
      array:[{a:0,b:0},{a:1,b:1},{a:2,b:2}]
     }

当我尝试访问它时,总是出现错误:

Property 'a' does not exist on type 'never'.

我认为我在这里声明一个接口很麻烦,找不到合适的方法来做到这一点。 这样的事情可能会做:

interface IState{
     array: object[]
}

组件的完整版本:

import * as React from "react";
import phrasalVerbs from "../data/phrasalVerbs";

interface IAnswerOptions {
   pVerb: string;
   meaning: string;
 }

interface IState {
  pVerbs: object;
  progress: number;
  answerOptions: IAnswerOptions[];
}

class PhrasalVerbs extends React.Component<{}, IState> {
  public state = {
    pVerbs: phrasalVerbs,
    progress: 0,
    answerOptions: []
  };

  public componentDidMount() {
    this.randomVariants();
  }

  public randomVariants = () => {
    let randomVariants: any[] = [];
    const currentVerbs = this.state.pVerbs.data;
    const shuffledVerbs = currentVerbs
      .map(a => [Math.random(), a])
      .sort((a: any, b: any): any => a[0] - b[0])
      .map(a => a[1]);
    randomVariants = [shuffledVerbs[0], shuffledVerbs[1], shuffledVerbs[2]];
    this.setState({
      ...this.state,
      answerOptions: randomVariants
    });
  };

  public render() {
    const { pVerbs, progress } = this.state;

    return (
      <div>
        <div>{pVerbs.data[progress].pVerb}</div>
        {/* <div>
          {this.state.answerOptions
            ? this.state.answerOptions[0].meaning
            : null}
        </div> */}
      </div>
    );
  }
}

export default PhrasalVerbs;

2 个答案:

答案 0 :(得分:2)

您可以为对象定义类型:

interface IMyObject {
    a: number;
    b: number;
}

interface IState {
    array: IMyObject[];
}

class MyComponent extends React.Component<any, IState> {
    state = {
        array:[{a:0,b:0},{a:1,b:1},{a:2,b:2}]
    };

    render() {
        // should be OK
        const firstA: number = this.state.array[0].a;

        return <h1>{firstA}</h1>;
    }
}

编辑:查看您的代码,您似乎意外地覆盖了state的类型。 Typescript会自动(有时是无用的)允许您覆盖类中的字段类型,因此,尽管您已根据IState定义了Component,但内部state属性的类型是由您为其赋予的默认值定义的。

在这种情况下,空数组的推断类型为never[],因此您最终得到了一个其元素无法使用的数组。

答案 1 :(得分:0)

嗯,您是否在tsconfig中设置了strictPropertyInitialization?