0

I have defined an object in TS like this:

reportObj : {
  'report' : {
    'pk' : '',
    'uploaded' : '',
    'sections' : {
      'section1' : '',
      'section2' : '',
      'section3' : ''
    }
  }
};

I want to set the value of section1. How can I do this? I am trying:

this.reportObj.report.sections.section1 = data;

This fails and I get the error:

Uncaught (in promise): TypeError: Cannot read property 'report' of undefined

What am I doing wrong?

3
  • Do that again without the this. prefix. Commented Jan 17, 2017 at 14:01
  • reportObj is a class member. Commented Jan 17, 2017 at 14:11
  • I defined it inside a function and straight away printed it in the console, but I get undefined. I don't think an object is being created. Commented Jan 17, 2017 at 14:18

1 Answer 1

1

The definition for the type should be:

reportObj: {
  'report': {
    'pk': string,
    'uploaded': string,
    'sections': {
      'section1': string,
      'section2': string,
      'section3': string
    }
  }
};

Edit

Defining the variable/member type doesn't assign a value to it.
This:

let reportObj: {
    report: {
        pk: string,
        uploaded: string,
        sections: {
            section1: string,
            section2: string,
            section3: string
        }
    }
};

console.log(reportObj.report);

Will fail at runtime because the variable reportObj only has a type, but not a value.
To assign a value:

type Reporter = {
    report: {
        pk: string,
        uploaded: string,
        sections: {
            section1: string,
            section2: string,
            section3: string
        }
    }
};

let reportObj = {} as Reporter;

console.log(reportObj.report); // undefined

But this will still throw a runtime error:

console.log(reportObj.report.pk);

This will assign the right value:

let reportObj = {
    report: {
        sections: {}
    }
} as Reporter;
Sign up to request clarification or add additional context in comments.

3 Comments

Check my revised answer
And after 6 hours of pain, Nitzan to the rescue! Thanks. I only hope the TS docs explained things this way.
If you use colon after the variable you define the type which is covered in the ts docs. If you use equals after the variable you assign a value which is just like it's done in javascript so the ts docs don't cover it.

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.