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
. 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. 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'.
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.
Property 'id' does not exist on type 'object'.
You have jockeys: Array<object>;
Change to jockeys: Array<{id: any}>;
or a similarly appropriate annotation.
Typescript is inferring that value
is of type object
which has no property id
. The way that the jockeys are being casted ( as object as
) also doesn't seem right. You should create a Jockey
interface to represent the jockey data structure and use that type definition instead of 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.