1

Why does assignment of a whole object work, but reassignment of a property doesn't (unless you use the property name as an index)? Does this make any sense at all?

var m: object ;

m = { name: 'qwerty' };  // works


m.name = 'xyz'; // does not work

m["name"] = 'abc'; // works

Still, I do not get when to use Object, object or {}, since all three match only to objects without any properties - which are pretty useless. Whenever I want to match objects with unknown properties, I refer to { [x:string] any} or any. So what is a practicable use case for these three?

2 Answers 2

4

Does this make any sense at all?

Yes, but there's several different type checking rules at play here.

object is basically a generic type that represents an object that has no known properties to the type checker. It allows you to assign any kind of object (non-primitive) to it with any kind of structure, because that's the point of it -- the similar Object and {} types also define no known properties, but allow primitives (like string) to be assigned, since Object is the base of all JS objects. object was added later as a means to express a non-primitive object. In any case (object, Object, or {}) when you try to access a specific property like m.name the type checker doesn't know what that is, so you get an error. The index based property assignment m["name"] has looser restrictions by default, even though the type checker still doesn't know what that is you don't get an error -- unless you turn on noImplicitAny then you do get an error on m["name"] saying:

Element implicitly has an 'any' type because type '{}' has no index signature.

This should point you in the right direction: if you want to describe an object with unknown properties of some type, you should define an index signature:

let m: { [key: string]: string; };

m = { name: 'qwerty' };  // works

m.name = 'xyz'; // works

m["name"] = 'abc'; // works
Sign up to request clarification or add additional context in comments.

Comments

1

All three assignments will work if m's type is {name: string}, or any.

The object type is relatively new, and I'd say you'd benefit from a more specific type, for example to catch errors like m.nmae = 'xyz'.

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.