1

Can someone please explain why you can't do this in Typescript?

this.obj.id = 1;
this.obj.str = 'This is string';

But you can do this:

this.obj = { id: 1, str: 'This is string'};
2
  • What is this.obj initially? If you didn't define it, you're trying to define properties on something that doesn't exist. Commented Jan 25, 2019 at 3:11
  • 2
    Because you cannot set property of undefined. Commented Jan 25, 2019 at 3:11

1 Answer 1

3

It's not a matter of you can't do but, you're doing it wrong. See Stackblitz Demo

I was able to define by using it like this:

obj = [];
obj2 = { id: 0, str: '' };
  
this.obj = { id: 1, str: 'This is string' };
this.obj2.id = 1;
this.obj2.str = 'This is string';
console.log(this.obj)
console.log(this.obj2)
  

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I already know why. You cannot set property of undefined. So you should initialize a default value or empty value.

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.