类型 {} 上不存在 Typescript 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49467069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript property does not exist on type {}
提问by Vayrex
I have the following code in Typescript. Why does the compiler throws an error?
我在Typescript 中有以下代码。为什么编译器会抛出错误?
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 '{}'.
js.ts(14,42):错误 TS2339:类型“{}”上不存在属性“first”。
It's the same code snippet like in the documentationof mozilla (examples section).
它与 mozilla文档(示例部分)中的代码片段相同。
回答by Vayrex
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
看看这个问题如何在TypeScript中自定义属性
回答by Emmanuel Osimosu
Make the object type any:
使对象类型为any:
var object: any = {};
回答by Suren Srapyan
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
.
那是因为 Typescript 是一种严格的类型语言。当您创建一个变量并为其指定类型时,您无法访问该类型中不存在的属性。添加额外的属性后不会强制编译器去寻找它。如果需要在创建后添加属性,请设置变量的类型any
。
回答by Aluan Haddad
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);