Typescript : Property does not exist on type 'object'

JavascriptTypescript

Javascript Problem Overview


I have the follow setup and when I loop through using for...of and get an error of : >Property "country" doesn't exist on type "object".

Is this a correct way to loop through each object in array and compare the object property value?

let countryProviders: object[];

export function GetAllProviders() {
   allProviders = [
      { region: "r 1", country: "US", locale: "en-us", company: "co 1" },
      { region: "r 2", country: "China", locale: "zh-cn", company: "co 2" },
      { region: "r 4", country: "Korea", locale: "ko-kr", company: "co 4" },
      { region: "r 5", country: "Japan", locale: "ja-jp", company: "co 5" }
   ]

   for (let providers of allProviders) {
      if (providers.country === "US") { // error here
         countryProviders.push(providers);
      }
   }
}

Javascript Solutions


Solution 1 - Javascript

You probably have allProviders typed as object[] as well. And property country does not exist on object. If you don't care about typing, you can declare both allProviders and countryProviders as Array<any>:

let countryProviders: Array<any>;
let allProviders: Array<any>;

If you do want static type checking. You can create an interface for the structure and use it:

interface Provider {
    region: string,
    country: string,
    locale: string,
    company: string
}

let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;

Solution 2 - Javascript

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

For your specific case try to define the key type and use Record utility to define the object :

type ProviderKey="region" | "country" | "locale" | "company"

let countryProviders: Array<Record<ProviderKey,string>>;

Solution 3 - Javascript

Yes the above methods are highly recommended, but if you have no choice and want to continue using "allProviders" as an array of object, then go for this method. This worked for me without creating an interface.

if(providers["country"] === "US") // replacement

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasonView Question on Stackoverflow
Solution 1 - JavascriptSaravanaView Answer on Stackoverflow
Solution 2 - JavascriptBoussadjra BrahimView Answer on Stackoverflow
Solution 3 - JavascriptHari Prasanna AddankiView Answer on Stackoverflow