TypeScript数字索引访问枚举映射模态对象返回undefined问题
问题原因
你用数字下标访问MODAL_TYPES始终得到undefined,本质是类型定义和实际对象结构完全不匹配:
- 你自定义的
Dict类型标注对象键为数字类型,但实际MODAL_TYPES的所有属性名都是字符串(比如ADD_NEW_USER、DELETE_CLASS),对象本身根本不存在数字键,用[0]、[2]这类数字索引访问必然返回undefined。 - 额外存在漏配问题:
Modals枚举第一个成员INVITE_NEW_USER对应数字值0,但你定义的MODAL_TYPES里完全没有这个键的配置,就算索引方式改对,传入值0时依然会找不到配置。
修复方法
方案1(推荐):用枚举值作为MODAL_TYPES的键
直接把MODAL_TYPES的键替换为Modals枚举成员,TS会自动做类型校验,既保证数字索引能正常访问,也能避免漏配:
首先导入Angular的Type类型用于标注组件类:
import { Type } from '@angular/core';
然后修改模态配置的定义:
export enum Modals { INVITE_NEW_USER, EDIT_USER, DELETE_CLASS, DELETE_STUDENT, BLOCK_STUDENT, ADD_NEW_CLASS, CLASS_PROFILE, EDIT_CLASSROOMS, ADD_NEW_USER_TO_CLASSROOM } export const MODAL_TYPES: Record<Modals, {component: Type<any>, title: string}> = { [Modals.INVITE_NEW_USER]: {component: InviteNewUserModalComponent, title: "Add New User"}, [Modals.EDIT_USER]: {component: EditUserModalComponent, title: "Edit User"}, [Modals.DELETE_CLASS]: {component: DeleteClassModalComponent, title: "Delete Class"}, [Modals.DELETE_STUDENT]: {component: DeleteStudentModalComponent, title: "Delete Student"}, [Modals.BLOCK_STUDENT]: {component: BlockStudentModalComponent, title: "Block Student"}, [Modals.ADD_NEW_CLASS]: {component: AddNewClassModalComponent, title: "Add new class"}, [Modals.CLASS_PROFILE]: {component: ClassProfileModalComponent, title: "Class Profile"}, [Modals.EDIT_CLASSROOMS]: {component: EditClassroomModalComponent, title: "Edit Classrooms"}, [Modals.ADD_NEW_USER_TO_CLASSROOM]: {component: AddNewUserModalComponent, title: "Add New User"}, } // 可以删除原来的Dict、ModalType冗余类型定义,用TS内置的Record类型更安全,避免any带来的类型问题
修改完成后,组件内原有访问逻辑不需要调整,this.modalTypes[this.modalType]就能正常拿到对应配置,TS还会在编译时检查你是否漏配了枚举对应的模态框,提前发现问题。
方案2:保留现有字符串键,访问时转换枚举值
如果不想改动现有MODAL_TYPES的结构,可以利用TS数字枚举的反向映射特性,先把传入的数字值转成对应的字符串键,再访问配置对象:
首先先补上MODAL_TYPES里缺失的INVITE_NEW_USER配置:
export const MODAL_TYPES = { INVITE_NEW_USER: {component: InviteNewUserModalComponent, title: "Add New User"}, ADD_NEW_USER: {component: InviteNewUserModalComponent, title: "Add New User"}, DELETE_CLASS: {component: DeleteClassModalComponent, title: "Delete Class"}, DELETE_STUDENT: {component: DeleteStudentModalComponent, title: "Delete Student"}, BLOCK_STUDENT: {component: BlockStudentModalComponent, title: "Block Student"}, ADD_NEW_CLASS: {component: AddNewClassModalComponent, title: "Add new class"}, CLASS_PROFILE: {component: ClassProfileModalComponent, title: "Class Profile"}, EDIT_CLASSROOMS: {component: EditClassroomModalComponent, title: "Edit Classrooms"}, ADD_NEW_USER_TO_CLASSROOM: {component: AddNewUserModalComponent, title: "Add New User"}, EDIT_USER: {component: EditUserModalComponent, title: "Edit User"}, }
然后修改组件内的访问逻辑:
ngOnInit(): void { // 数字转枚举对应的字符串键 const modalKey = Modals[this.modalType] as keyof typeof MODAL_TYPES; const currentConfig = MODAL_TYPES[modalKey]; this.modal = currentConfig.title; this.viewContainerRef.createComponent(currentConfig.component); }
内容的提问来源于stack exchange,提问作者user2004
相关产品推荐
相关产品推荐

