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).
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
使物体的任何类型:
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
.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.