类型{}上没有Typescript属性 [英] Typescript property does not exist on type {}

查看:105
本文介绍了类型{}上没有Typescript属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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):错误TS2339:类型上不存在属性"first" '{}'.

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

文档(示例部分).

推荐答案

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

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);

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

这篇关于类型{}上没有Typescript属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆