Typescript property does not exist on type {}

前端 未结 4 1817
我寻月下人不归
我寻月下人不归 2020-12-02 01:00

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

var object = {};
Object.defineProperty(object, \'first\', {
         


        
4条回答
  •  天命终不由人
    2020-12-02 01:23

    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

提交回复
热议问题