Typescript property does not exist on type {}

前端 未结 4 1796
我寻月下人不归
我寻月下人不归 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:08

    Make the object type any:

    var object: any = {};
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-02 01:23

    In the given case, I would just rewrite it as

    var object = {};
    
    var withFirst =  {...object, get first() {return 37;}};
    
    console.log('first property: ' + withFirst.first);
    
    0 讨论(0)
  • 2020-12-02 01:35

    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.

    0 讨论(0)
提交回复
热议问题