简体   繁体   English

Angular - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型

[英]Angular - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

I have this code in Angular-13:我在 Angular-13 中有这段代码:

export class ShowValidationErrorsComponent {

 private static readonly errorMessages = {
    'required': () => 'This field is required.',
    'minlength': (params: { requiredLength: any; }) => `Value must be at least' ${params.requiredLength} characters long.`,
    'maxlength': (params: { requiredLength: any; }) => `Value must be shorter than ${params.requiredLength} characters.`,
    'pattern': (params: { requiredPattern: string; }) => 'The required pattern is: ' + params.requiredPattern
 };

 @Input() private control!: AbstractControlDirective | AbstractControl;
 @Input() private shouldShow: boolean = true;
 @Input() extraCssClasses: string = '';

   showList(): boolean {
    return !!(this.control &&
      this.control.errors &&
      this.shouldShow);
  }

  listOfErrors(): string[] {
    let errors: string[] = [];
    for (let field of Object.keys(this.control.errors!)) {
      if (field in ShowValidationErrorsComponent.errorMessages) {
        errors.push(ShowValidationErrorsComponent.errorMessages[field](this.control.errors![field]));
      }
      else if ('message' in this.control.errors![field]) {
        errors.push(this.control.errors![field].message);
      }
    }
    return errors;
  }
}

which I used for validation.我用它来验证。 But I got this error:但是我得到了这个错误:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ required: () => string;元素隐含地具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ required: () => string; minlength: (params: { requiredLength: any; }) => string;最小长度:(参数:{requiredLength:任何;})=>字符串; maxlength: (params: { requiredLength: any; }) => string;最大长度:(参数:{requiredLength:任何;})=>字符串; pattern: (params: { requiredPattern: string; }) => string;模式:(参数:{requiredPattern:字符串;})=>字符串; }'. }'。 No index signature with a parameter of type 'string' was found on type '{ required: () => string;在类型“{ required: () => string; 上找不到参数类型为“string”的索引签名min分钟

This line of code is highlighted:这行代码高亮显示:

ShowValidationErrorsComponent.errorMessages[field] ShowValidationErrorsComponent.errorMessages[字段]

in

errors.push(ShowValidationErrorsComponent.errorMessagesfield); errors.push(ShowValidationErrorsComponent.errorMessagesfield);

What do I do to get it resolve?我该怎么做才能解决它?

Thanks谢谢

This happens because the implicit type of errorMessages is the following:发生这种情况是因为errorMessages的隐式类型如下:

type ErrorMessagesType = {
    required: () => string;
    minlength: (params: { requiredLength: any }) => string;
    maxlength: (params: { requiredLength: any }) => string;
    pattern: (params: { requiredPattern: string }) => string;
}

As you can see, this is very specific to the point that it exactly matches the structure of your errorMessages value.如您所见,这是非常具体的,因为它与您的errorMessages值的结构完全匹配。 This is because the compiler cannot make a safe guess to what your intention with that type was.这是因为编译器无法安全地猜测您对该类型的意图 So instead, it constructs the type based on what the value actually contains.因此,它根据值实际包含的内容构造类型。

Usually, this works very well, allowing you to use the type with strong type safety everywhere.通常,这非常有效,允许您在任何地方使用具有强类型安全性的类型。 But it breaks quickly when you want to access things dynamically.但是当您想动态访问事物时,它很快就会崩溃。

In your case, you check that the field is a valid key of that errorMessages object using field in ShowValidationErrorsComponent.errorMessages .在您的情况下,您使用field in ShowValidationErrorsComponent.errorMessages中的字段检查该field是否是errorMessages object 的有效键。 With this, the compiler knows that doing errorMessages[field] itself is safe to access.有了这个,编译器就知道执行errorMessages[field]本身是可以安全访问的。 But it has no idea which of the values you access so it cannot guess the actual type of the result.但它不知道您访问了哪些值,因此无法猜测结果的实际类型。

In the end, for situations like this, you should consider specifying an explicit type that matches your intention.最后,对于这种情况,您应该考虑指定一个符合您意图的显式类型。 In this case, I would assume that you want some kind of mapping from a field name to a validation function. You can use the Record<K, T> type for this:在这种情况下,我假设您需要某种从字段名称到验证 function 的映射。您可以为此使用Record<K, T>类型:

private static readonly errorMessages: Record<string, Function> = {
    'required': () => 'This field is required.',
    'minlength': (params: { requiredLength: any; }) => `Value must be at least' ${params.requiredLength} characters long.`,
    'maxlength': (params: { requiredLength: any; }) => `Value must be shorter than ${params.requiredLength} characters.`,
    'pattern': (params: { requiredPattern: string; }) => 'The required pattern is: ' + params.requiredPattern
};

Unfortunately, your validation functions do not share a common shape, so you cannot get a much better type there than just knowing that it's a function. So that's what you can use there.不幸的是,您的验证函数不具有共同的形状,因此除了知道它是 function 之外,您无法获得更好的类型。所以这就是您可以在那里使用的类型。

With this, the compiler will at least be able to properly resolve the errorMessages[field] access and tell that the result is a function that it can call.有了这个,编译器至少能够正确解析errorMessages[field]访问并告知结果是它可以调用的 function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引 Angular 中的类型 - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type in Angular 元素隐式具有“任何”类型,因为类型“徽标”的表达式不能用于索引 Angular 中的类型“对象” - Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object' in Angular TypeScript - 元素隐式具有“任何”类型,因为类型“字符串”的表达式不能用于索引类型“TestObject” - TypeScript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'TestObject ' 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“搜索查询” - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SearchQuery' '元素隐式具有'any'类型,因为'string'类型的表达式不能用于*ngFor中的Object中的类型索引 - 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type in Object' in *ngFor 元素隐式具有“任何”类型,因为“_popupComponentRef”类型的表达式不能用于索引类型“MatDatepicker”<Date> &#39; - Element implicitly has an 'any' type because expression of type '"_popupComponentRef"' can't be used to index type 'MatDatepicker<Date>' 元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引“对象”类型 - Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'Object' 元素隐式具有“任何”类型,因为“名称”类型的表达式不能用于索引类型“对象” - Element implicitly has an 'any' type because expression of type '"name"' can't be used to index type 'Object' 元素隐式具有“任何”类型,因为“事件组”类型的表达式不能用于索引类型“MonthViewDay”<eventgroupmeta> '</eventgroupmeta> - Element implicitly has an 'any' type because expression of type '"eventGroups"' can't be used to index type 'MonthViewDay<EventGroupMeta>' 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“(controlName: string) => boolean” - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '(controlName: string) => boolean'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM