![](/img/trans.png)
[英]Troubles with array of objects inside my interface in TypeScript & Reactjs
[英]Troubles with array of objects interface in 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;
您可以为对象定义类型:
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[]
,因此您最终得到一个数组,该数组的元素无法使用。
嗯,您是否在tsconfig中设置了strictPropertyInitialization?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.