1
votes

i am writing a object with typescript, the code is:

const obj2 ={name:1}
obj2.name = 2;
console.log(obj2.name)
const obj3:object = {name: "wewda"}
obj3.name = 'dadsa';
obj3['name'] = "cxzcxz"
console.log(typeof obj2)
console.log(obj3)
console.log(typeof obj3)

I got an error in line 5: error TS2339: Property 'name' does not exist on type 'object'. but if i use obj3['name'] = "cxzcxz" instead, it works, can anyone explain? thank you

1

1 Answers

5
votes

Look at this line:

const obj3:object = {name: "wewda"};

You've explicitly declared that obj3 is of type object, effectively discarding any information about what properties the object can contain. The type object, by the way, is a type that represents the non-primitive type, i.e. anything that is not number, string, boolean, symbol, null, or undefined.

So there's no way that the type system can verify that obj3.name is valid. However, if you're running with the default compiler options (which are rather lax), obj3['name'] will be allowed because obj3 will be implicitly cast to any, even though in principle it's equally unsafe. I generally recommended that you enable the --noImplicitAny compiler option to guard against this kind of unsafe access.

Note also that this is a compile-time error in your typings, not a run-time error. In other words, the value of obj3 still has the property name, but the type object does not.