0

One question about Objects in JS ( typescript ). I have following code which works fine

myObj: { type: string } = { type: '' };
this.myObj.type = 'Abcd';

But i want this code to work

myObj: { type: string };
this.myObj.type = 'abcd'; // this.myObj['type'] = 'Abcd'; also not working

Why is it not working? What am i doing wrong? I am getting 'cannot set property type of null'

1 Answer 1

1

This:

let myObj: { type: string };

Compiles to this javascript:

var myObj;

As you can see, you're not assigning a value to it, so if you'll try to do:

myObj.type = "what not";

You'll get an error becaue myObj is undefined.

You can do this:

let myObj = { type: '' };

The compiler will infer the right type for myObj.
This way it will have a value and you won't have to write both the value and the type.

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

3 Comments

So if i do let myObj = { }; and after this myObj['type']='abcd'; it's ok?
Yes, but you won't have type safety.
sadly, thought that i can do this without initialization. Okay, thanks :)

Your Answer

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