Angular13中icons[icon]报string无法索引对象隐式any错解决方法
报错原因
这个TypeScript报错由严格类型检查规则触发:
- 你定义的
icons对象默认被TS推导为拥有3个固定键的对象类型,键的类型为字面量联合类型'facebook' | 'google' | 'googlePlus',仅允许这三个字符串作为索引键 - 你的
icon输入属性被标注为宽泛的string | null类型,TS无法确认传入的字符串一定是icons对象上存在的键,出于类型安全考虑抛出错误 - 你之前修改
icon的初始化写法没有改变icon的宽泛string类型本质,因此无法消除报错。
修复方案
根据你对类型严格度的需求,二选一即可:
方案1(推荐,类型安全性最高)
将icon输入的类型严格限定为icons对象支持的键名,TS会自动做类型校验,传入不存在的图标名时会提前编译报错,避免运行时异常。
修改button.component.ts对应代码:
import {Component, Input} from '@angular/core'; @Component({ selector: 'app-button', templateUrl: './button.component.html', styleUrls: ['./button.component.scss'] }) export class ButtonComponent { @Input() type: string = 'button'; @Input() block: boolean = false; @Input() color: string = 'primary'; @Input() disabled: boolean = false; @Input() loading: boolean = false; // 限定icon只能是icons中存在的键,或null @Input() icon: keyof ButtonComponent['icons'] | null = null; // 加as const精确推导对象类型 public icons = { facebook: 'fab fa-facebook', google: 'fab fa-google', googlePlus: 'fab fa-google-plus' } as const; constructor() {} }
后续如果需要新增支持的图标,只需要在icons对象里加对应键值对即可,TS会自动同步更新允许的icon输入类型,不需要额外修改类型定义。
方案2(灵活度高,类型检查宽松)
如果你需要允许传入任意字符串作为图标键名(比如后续动态扩展图标类、支持外部传入自定义图标类),可以给icons对象添加字符串索引签名,告诉TS任意字符串键都可以访问到字符串类型的值。
修改button.component.ts中icons的类型定义:
// 用Record类型定义对象为string键、string值的结构 public icons: Record<string, string> = { facebook: 'fab fa-facebook', google: 'fab fa-google', googlePlus: 'fab fa-google-plus' };
这种写法不需要修改icon的原有类型定义,但是如果传入了icons中不存在的键名,TS不会提前报错,需要自行保证传入值的正确性。
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

