mic_test
mic_test

Reputation: 161

How to ignore this "Property 'methods' does not exist on type" in Typescript?

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

Answers (2)

Rafi Henig
Rafi Henig

Reputation: 6432

Unsafe but shorter if your are sure methods exists:

for (let index = 0; index < (<any>this.data).methods.length; index++) 

Upvotes: 0

Donovan Hiland
Donovan Hiland

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.

  1. You can assign a type that you've defined to the JSON objects:
interface Data {
  methods?: { id: string, name: string }[]
}

data: Data = {
  ....
}

// this.data.methods exists now and can be checked
if (this.data.methods) {}
  1. Use a user defined type guard:
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

Related Questions