1

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?

2
  • It seems that error appears when the lastFiveMatches.length === 0. Commented Oct 16, 2019 at 7:11
  • He would get "Cannot read property of undefined" if length === 0. Problem is that he doesn't have typed lastFiveResults property. Commented Oct 16, 2019 at 7:16

6 Answers 6

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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[];

}

Comments

0
export class Stats {
    lastFiveResults: Object[]=[{…}, {…}, {…}, {…}, {…}]
}

in your ts file:

data= new Stats();
console.log(data.lastFiveMatches[0].gold)

Comments

0

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.

Comments

0

Try this:

if (data.lastFiveMatches && data.lastFiveMatches.length > 0) {    
   const something = data.lastFiveMatches[0].gold || 0;
}

Comments

0

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);    
}  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.