[英]error mapping array to string with Object.keys (javascript)
I have an object of type c.errors that returns, in a specific case: 在特定情况下,我有一个类型为c.errors的对象返回:
{ required: true}
{必填:true}
And I want to map this against the more general (and fixed array) 我想将其映射到更通用的(和固定数组)
validationMessages = {
required: 'Please enter',
pattern: 'Please enter valid'
}
I also have an errorMessage property initialised with an empty string . 我也有一个用空字符串初始化的errorMessage属性。 My attempt was:
我的尝试是:
this.errorMessage = Object.keys((c.errors).map(key => this.validationMessages[key]).join(' '));
Errors I get: 我得到的错误:
Parameter 'key' implicitly has an 'any' type.
参数“键”隐式具有“任意”类型。
Element implicitly has an 'any' type because type '{ required: string;
元素隐式地具有“ any”类型,因为类型“ {{required:string; pattern: string;
模式:字符串; }' has no index signature.
}'没有索引签名。
Any advice? 有什么建议吗?
this.errorMessage should contain 'Please enter' (that's my expectation after mapping) this.errorMessage应该包含“请输入”(这是我在映射后的期望)
If you index into a type that does not have an indexer, typescript expects the string you index by to be a key of the type. 如果您索引到没有索引器的类型,则打字稿期望您通过其索引的字符串是该类型的键。 This means that in you case,
key
should be either string literal type 'required'
or 'pattern'
. 这意味着在您的情况下,
key
应为字符串文字类型'required'
或'pattern'
。 Since Object.keys
returns an array of strings
, if you are certain that array will only contain valid keys for validationMessages
you can just use a type assertion. 由于
Object.keys
返回一个strings
数组,因此,如果可以确定该数组将仅包含validationMessages
有效键,则可以使用类型断言。 Also you have some mismatched parenthesis: 另外,您还有一些不匹配的括号:
this.errorMessage = Object.keys(c.errors).map((key) => this.validationMessages[key as 'required']).join(' ');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.