类型{}不存在Typescript属性

3 javascript typescript

我在Typescript中有以下代码。为什么编译器会引发错误?

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

js.ts(14,42):错误TS2339:类型“ {}”上不存在属性“ first”。

与mozilla 的文档(示例部分)中的代码段相同。

Emm*_*osu 8

使对象类型为any

var object: any = {};
Run Code Online (Sandbox Code Playgroud)

  • 关闭类型保护有点违背了使用 TypeScript 的目的。 (2认同)

Vay*_*rex 5

另一种方法是做接口,因此编译器将知道该属性存在。

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);
Run Code Online (Sandbox Code Playgroud)

看看这个问题如何在TypeScript中自定义属性