typescript “对象”类型上不存在属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43338763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:41:31  来源:igfitidea点击:

Property does not exist on type 'object'

typescript

提问by Jason Tang

I have the follow setup and when I loop through using for...ofand get an error of Property "country" doesn not exist on type "object". Is this a correct way to loop through each object in array and compare the object property value?

我有以下设置,当我循环使用for...of并得到属性“国家”的错误时,类型“对象”不存在。这是循环遍历数组中的每个对象并比较对象属性值的正确方法吗?

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);
      }
   }
}

回答by Saravana

You probably have allProviderstyped as object[]as well. And property countrydoes not exist on object. If you don't care about typing, you can declare both allProvidersand countryProvidersas Array<any>:

你可能也allProviders打过字object[]。并且country在 上不存在财产object。如果你不关心打字,你可以同时声明allProviderscountryProvidersArray<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>;