Reputation: 161
I have a JSON object, i want to get the "methods" (one of the properties in the JSON object), but the "methods" sometimes exist sometimes does not exist. How can I check if exist, then only run my function, if does not exist, it will not jump this error "Property 'methods' does not exist on type" in typescript.
No error
data = {
...
methods: [{ id:1, name:"abc"},{ id:2, name:"def"}]
...
};
if (this.data.methods) {
// this for loop no jump any error
for (let index = 0; index < this.data.methods.length; index++) {
...
}
}
Error
data = {
....
}
if (this.data.methods) {
// this for loop jump error "Property 'methods' does not exist on type"
for (let index = 0; index < this.data.methods.length; index++) {
....
}
}
Upvotes: 1
Views: 1853
Reputation: 6432
Unsafe but shorter if your are sure methods
exists:
for (let index = 0; index < (<any>this.data).methods.length; index++)
Upvotes: 0
Reputation: 1499
The reason this is happening is because the type of the object is being inferred by the JSON structure. It's being inferred as NOT having a methods
property, so trying to access a methods property even to check if it exists is not valid. It can't exist. You need to tell typescript this object can have that property before checking for referencing it.
There are a couple ways you can do this.
interface Data {
methods?: { id: string, name: string }[]
}
data: Data = {
....
}
// this.data.methods exists now and can be checked
if (this.data.methods) {}
interface Data {
methods?: { id: string, name: string }[]
}
const hasMethods = (data: any): data is Data => Boolean(data.methods)
data = {
....
}
if (hasMethods(data)) {
// this.data.methods exists now and can be checked
}
Upvotes: 1