Reputation: 2689
I have an interface that looks like this:
export interface Stats {
lastFiveResults: Object[];
}
The array of objects looks this this:
(5) [{…}, {…}, {…}, {…}, {…}]
0: {idresults: 500, gold: 567740, mana: 305370, xp: 1800}
1: {idresults: 501, gold: 492381, mana: 602707, xp: 1450}
2: {idresults: 502, gold: 241012, mana: 303954, xp: 810}
3: {idresults: 503, gold: 415778, mana: 261254, xp: 810}
4: {idresults: 504, gold: 327266, mana: 427803, xp: 0}
And when I try and access it like this
data.lastFiveMatches[0].gold
I get Property gold does not exist on type object
So my question is how do I specify these properties?
Upvotes: 1
Views: 57
Reputation: 38134
You can declare like this:
export interface Stat {
idresults: number,
gold: number,
mana: number,
xp: number
}
and to initialize:
yourStats: Stat[]= [];
fooMethod() {
for (let i = 0; i<10; i++) {
console.log('1');
this.yourStats.push({idresults: i, gold: i, mana: i, xp: i})
}
console.log(`Your stats is`, this.yourStats);
}
Upvotes: 0
Reputation: 595
Try this:
if (data.lastFiveMatches && data.lastFiveMatches.length > 0) {
const something = data.lastFiveMatches[0].gold || 0;
}
Upvotes: 0
Reputation: 19070
You should create the interfaces Item
and ResultItem
:
export interface ResultItem {
idresults: number;
gold: number;
mana: number;
xp: number;
}
export interface Stats {
lastFiveResults: ResultItem[];
}
... and then:
data.lastFiveMatches[0].gold;
Upvotes: 1
Reputation: 5524
You can define interface
or type
for your object within the list
export interface Stats {
lastFiveResults: MyObject[];
}
export interface MyObject {
idresults: number
gold: number
mana: number
xp: number
}
Please see this playground.
Upvotes: 0
Reputation: 551
export class Stats {
lastFiveResults: Object[]=[{…}, {…}, {…}, {…}, {…}]
}
in your ts file:
data= new Stats();
console.log(data.lastFiveMatches[0].gold)
Upvotes: 0
Reputation: 4884
You can define another interface to specify the type of properties in your object.
interface myObject {
idresults: number,
gold: number,
mana: number,
xp: number
}
export interface Stats {
lastFiveResults: myObject[];
}
Upvotes: 0