12

I have the following code in Typescript. Why does the compiler throws an error?

var object = {};
Object.defineProperty(object, 'first', {
     value: 37,
     writable: false,
     enumerable: true,
     configurable: true
});
console.log('first property: ' + object.first);

js.ts(14,42): error TS2339: Property 'first' does not exist on type '{}'.

It's the same code snippet like in the documentation of mozilla (examples section).

3 Answers3

9

Another way is to do interface, so compiler will know that property exists.

interface IFirst{
  first:number;
}


let object = {} as IFirst;
Object.defineProperty(object, 'first', {
  value: 37,
  writable: false,
  enumerable: true,
  configurable: true
});
console.log('first property: ' + object.first);

Take a look at this question How to customize properties in TypeScript

Vayrex
  • 1,417
  • 1
  • 11
  • 13
  • It works fine. But is this the propper way to do it? ps: first should be of type number in your interface –  Mar 24 '18 at 16:43
  • 1
    I think the line `let object = {} as IFirst;` will throw error cause the `first` property is required and missed in the type – Suren Srapyan Mar 24 '18 at 16:47
  • `const CONFIG_CACHE = {} as Config` works great... it's a shame such a small change isn't suggested in the hints. I now get t he reasoning of why `const CONFIG_CACHE: Config = {} ` doesn't work in hindsight. – Ray Foss Apr 19 '22 at 16:50
8

Make the object type any:

var object: any = {};
Emmanuel Osimosu
  • 5,625
  • 2
  • 38
  • 39
0

That's because Typescript is a strict type language. When you create a variable and give to it a type, you can't access properties that does not exists in that type. After adding extra property will not force the compiler to look for it. If you need to add a property after the creation, make the type of your variable any.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • 2
    Better to add an index signature `[k: string]: any` to the type instead of disabling all validation and all intellisense. – Aluan Haddad Mar 24 '18 at 20:26