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
Property does not exist on type 'object'
提问by Jason Tang
I have the follow setup and when I loop through using for...of
and 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 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>
:
你可能也allProviders
打过字object[]
。并且country
在 上不存在财产object
。如果你不关心打字,你可以同时声明allProviders
和countryProviders
为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>;