admin管理员组文章数量:1201593
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): error TS2339: Property 'first' does not exist on type '{}'.
It's the same code snippet like in the documentation of mozilla (examples section).
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): error TS2339: Property 'first' does not exist on type '{}'.
It's the same code snippet like in the documentation of mozilla (examples section).
Share Improve this question asked Mar 24, 2018 at 16:24 user2685879user2685879 1 |3 Answers
Reset to default 9Another 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
Make the object type any:
var object: any = {};
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
.
本文标签: javascriptTypescript property does not exist on type Stack Overflow
版权声明:本文标题:javascript - Typescript property does not exist on type {} - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738551063a2097379.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
readonly
? – Jonas Wilms Commented Mar 24, 2018 at 17:04