0

Typescript claims full compatibility with JavaScript, but yet when I write:

var obj = {};
obj.x = 1;

TypeScript throws an error saying that obj doesn't have definition of x. Why?

I am using VS2013 along with TypeScript 1.4

meetar
  • 7,443
  • 8
  • 42
  • 73
imgen
  • 2,803
  • 7
  • 44
  • 64
  • Related: [How do I dynamically assign properties to an object in TypeScript?](http://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in-typescript) – Jonathan Lonowski Apr 22 '15 at 03:38
  • 1
    To answer to "why": this is because of the [TS inference](http://www.typescriptlang.org/Handbook#type-inference). The type of the variable `obj` is implicitly inferred from the empty object. – Paleo Apr 22 '15 at 08:07
  • 1
    To address your first sentence: valid JavaScript *is* valid TypeScript, but TypeScript is more strict with what it considers valid. For example, `var a = 1; a = "name";` is also valid JavaScript, but TypeScript will throw an error, also because of type inference. Same thing with trying to get or set a property that doesn't exist, like your example. To make your intentions explicit to the compiler, either declare it as of type `any`, or use `obj["x"] = 1;` instead. – zeh Apr 22 '15 at 15:54
  • @Tarth, I now understand! After playing with TypeScript a bit more and with your explanations, now I fully understand this issue – imgen Apr 23 '15 at 06:22

0 Answers0