在TypeScript泛型类中定义嵌套对象的正确方式是什么?
错误原因
你当前的SidenavOptions类仅声明了嵌套属性的类型结构,没有在类内部完成嵌套对象的初始化。当你执行new SidenavOptions()时,生成的实例中container属性默认是undefined,此时直接访问container.styles就会触发Cannot read properties of undefined类报错。
正确实现方式
方案1:类内添加构造函数完成嵌套对象初始化
直接在类的构造函数中给所有嵌套层级的属性赋初始值,保证实例生成后所有属性都可用:
export class SidenavOptions { autoWidth: boolean; container: { styles: { width: string, height: string, backgroundColor: string, } }; constructor() { // 给基础属性设默认值 this.autoWidth = false; // 逐层初始化嵌套对象 this.container = { styles: { width: '', height: '', backgroundColor: '' } } } }
初始化后你原来的赋值逻辑this.hasOptions.container.styles.backgroundColor = "black";就可以正常运行。
方案2:构造函数支持传参自定义初始值
如果需要灵活设置初始属性,可以给构造函数加可选参数,支持传入配置直接生成符合要求的实例:
export class SidenavOptions { autoWidth: boolean; container: { styles: { width: string, height: string, backgroundColor: string, } }; constructor(opts?: Partial<SidenavOptions>) { this.autoWidth = opts?.autoWidth ?? false; // 优先用传入的配置,没有传就用默认值 this.container = opts?.container ?? { styles: { width: '', height: '', backgroundColor: '' } }; } } // 使用示例 bindOptions(): SidenavOptions { // 直接传入需要自定义的属性即可 this.hasOptions = new SidenavOptions({ container: { styles: { backgroundColor: "black", width: "240px", height: "100vh" } } }); return this.hasOptions; }
方案3:用接口替代类(仅需类型约束场景)
如果你不需要用类实现方法、仅需要对数据结构做类型约束,用interface会更简洁:
export interface SidenavOptions { autoWidth: boolean; container: { styles: { width: string, height: string, backgroundColor: string, } }; } // 使用时直接初始化完整对象 bindOptions(): SidenavOptions { this.hasOptions = { autoWidth: false, container: { styles: { width: '', height: '', backgroundColor: "black" } } }; return this.hasOptions; }
内容的提问来源于stack exchange,提问作者Ahmer Ali Ahsan
相关产品推荐
相关产品推荐

