Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  126] [ 4]  / answers: 1 / hits: 60624  / 9 Years ago, thu, may 7, 2015, 12:00:00

If TypeScript is a strict superset of JavaScript, why is dot notation on an arbitrary object erroneous? I have JS code that I want to convert over to TS for better type safety, but all access using dot notation (eg, myObj.thing) gives me the error Property 'thing' does not exist on type '{}'.. It works properly when I use bracket notation (eg, myObj['thing']).



Property


More From » typescript

 Answers
21

I know you say this is odd, but this is one of the main reasons TypeScript exists. This error helps prevent accidentally setting or getting non-existent properties on an object.



Right now, as the compiler is telling you, the property bar does not exist on x because it has been implicitly typed to {} when writing var x = {};.



You can tell the compiler that x has more than zero properties by explicitly defining the type:



var x: { foo?: string; bar?: string; } = {};


Now you can get or set x.foo and x.bar without the compiler complaining. In most cases, you would move this into an interface like so:



interface IFooBar {
foo?: string;
bar?: string;
}

var x: IFooBar = {};

x.foo = asdf; // ok
x.test = asdf; // error, as it should be


Some people are recommending you cast to any, but don't get lazy. You should make full use of the type system TypeScript provides. Doing so will most definitely save you time down the road as you maintain an application.


[#66707] Tuesday, May 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
diane

Total Points: 264
Total Questions: 104
Total Answers: 95

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;