[英]React/Typescript: Property 'id' does not exist on type 'object'
I import data from a different file but in render()
I can't seem to get the properties eg id
of the entities in json data
. 我从另一个文件导入数据,但是在render()
我似乎无法获取属性,例如json data
实体的id
。 On debug, I can actually see the id
eg 233765 when I hover the mouse over it but typescript for some reason gives the error here below the code. 在调试时,当我将鼠标悬停在id
上时,我实际上可以看到其id
例如233765,但是由于某种原因,打字稿在代码下方给出了错误。 Where's the fault in my definitions? 我的定义哪里出问题了?
import * as React from 'react'; import * as data from '../../team.json'; interface Props { //props } interface State { nextRacers: Array<object>; jockeys: Array<object>; } export class Race extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { jockeys: data as object as <ArrayObject>, nextRacers: [], }; } render() { const r = this.state.jockeys; const x = r.map((value, i) => { console.log(value.id); }); console.log(x); } }
I get an error; 我得到一个错误;
Property 'id' does not exist on type 'object'. 属性“ id”在类型“ object”上不存在。
I've googled quite extensively with many results poppin but cant seem to apply the logic to this simple thing I'm trying to do. 我已经在Google搜索中广泛搜索了很多结果poppin,但似乎无法将逻辑应用于我尝试做的这个简单事情。
Property 'id' does not exist on type 'object'. 属性“ id”在类型“ object”上不存在。
You have jockeys: Array<object>;
您有jockeys: Array<object>;
Change to jockeys: Array<{id: any}>;
更改为jockeys: Array<{id: any}>;
or a similarly appropriate annotation. 或类似的适当注释。
Typescript is inferring that value
is of type object
which has no property id
. Typescript推断该value
是没有属性id
object
类型。 The way that the jockeys are being casted ( as object as
) also doesn't seem right. 骑师( as object as
)的投射方式似乎也不对。 You should create a Jockey
interface to represent the jockey data structure and use that type definition instead of object
. 您应该创建一个Jockey
接口来表示jockey数据结构,并使用该类型定义代替object
。
import * as React from 'react';
import * as data from '../../team.json';
interface Jockey {
id: string;
}
interface Props {
//props
}
interface State {
nextRacers: any[];
jockeys: Jockey[];
}
export class Race extends React.Component<Props, State> {
state: State;
constructor(props: Props) {
super(props);
this.state = {
jockeys: data as Jockey[],
nextRacers: []
};
}
render() {
const r = this.state.jockeys;
const x = r.map((value: Jockey, i: number) => {
console.log(value.id);
});
console.log(x);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.