[英]How to typify a nested object?
How to typify a nested object?如何典型化嵌套的 object?
enter image description here在此处输入图像描述
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ UA: {};元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ UA: {}; RU: {};鲁:{}; }'. }'。 No index signature with a parameter of type 'string' was found on type '{ UA: {};在类型 '{ UA: {}; 上找不到具有类型参数的索引签名RU: {};鲁:{}; }'. }'。 TS7053 TS7053
interface IState {
showInfo: any,
priceVariantIndex: any,
loaded: any,
imgLoaded: any,
imgUrl: any,
selectedCutlery: any,
product: any,
}
state = {
showInfo: false,
priceVariantIndex: 0,
loaded: false,
imgLoaded: false,
imgUrl: '',
selectedCutlery: '',
product: {
productTranslations: {
UA: {},
RU: {}
}
}
}
<Link to={linkObject}>
{this.props.language &&
this.state.product.productTranslations[`${this.props.language}`]
.name != undefined
? this.state.product.productTranslations[
`${this.props.language}` // err
].name
: product.name}
</Link>
The conflict here is between the type of language
in props
, which is a string
and the type of productTranslations
which is type { UA: {}, RU: {} }
.这里的冲突是props
中的language
类型( string
)和productTranslations
类型(类型为{ UA: {}, RU: {} }
)之间的冲突。
If you don't want to explicitly type of language
to the specific letter-codes that you are using to represent languages, you can update your product
type in the IState
interface to如果您不想将语言类型显式指定为用于表示language
的特定字母代码,则可以将IState
界面中的product
类型更新为
product: { productTranslations: { [language: string]: any } };
Which now says that this.state.product
has a productTranslations
property which is a mapping of string
to any
.现在说this.state.product
有一个productTranslations
属性,它是string
到any
的映射。
As an aside, I'd highly recommend eliminating all of those any
types, or at least change them to unknown
so that you don't run into issues that TypeScript could definitely have caught for you.顺便说一句,我强烈建议消除所有any
类型,或者至少将它们更改为unknown
,这样您就不会遇到 TypeScript 肯定会为您发现的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.