Angular集成Bryntum Scheduler遇类型错误:'undefined'无法赋值
Angular Bryntum Scheduler 绑定columns时类型错误解决
问题详情
编译Angular项目时触发类型错误:
类型“undefined”不可分配给类型“object | object[] | ColumnStore | Partial
| Partial []”。
5 [columns] = "schedulerConfig.columns"
相关代码如下:
app.component.html
<bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedulerConfig.columns" [startDate] = "schedulerConfig.startDate!" [endDate] = "schedulerConfig.endDate!" ></bryntum-scheduler>
app.component.ts
import { Component, ViewChild } from '@angular/core'; import { BryntumSchedulerComponent } from '@bryntum/scheduler-angular'; import { schedulerConfig } from './app.config'; @Component({ selector : 'app-root', templateUrl : './app.component.html', styleUrls : ['./app.component.scss'] }) export class AppComponent { resources = [ { id : 1, name : 'Dan Stevenson' }, { id : 2, name : 'Talisha Babin' } ]; events = [ { resourceId : 1, startDate : '2022-01-01', endDate : '2022-01-10' }, { resourceId : 2, startDate : '2022-01-02', endDate : '2022-01-09' } ]; schedulerConfig = schedulerConfig; @ViewChild('scheduler') schedulerComponent!: BryntumSchedulerComponent; }
app.config.ts
import { SchedulerConfig } from '@bryntum/scheduler'; export const schedulerConfig: Partial<SchedulerConfig> = { columns : [ { text : 'Name', field : 'name', width : 160 } ], startDate : new Date(2022, 10, 17), endDate : new Date(2022, 10, 23) };
错误原因
app.config.ts中schedulerConfig被定义为Partial<SchedulerConfig>,Partial类型会将原类型的所有属性转为可选,因此TypeScript判定schedulerConfig.columns可能为undefined。但Bryntum Scheduler的columns输入属性不接受undefined类型,导致类型不匹配报错。
解决方法
方案1:移除Partial类型断言
直接使用SchedulerConfig类型定义配置对象,确保所有必填属性都已声明:
// app.config.ts import { SchedulerConfig } from '@bryntum/scheduler'; export const schedulerConfig: SchedulerConfig = { columns : [ { text : 'Name', field : 'name', width : 160 } ], startDate : new Date(2022, 10, 17), endDate : new Date(2022, 10, 23) // 若SchedulerConfig存在其他必填属性,需补充完整 };
方案2:模板中使用非空断言
在模板的columns绑定后添加!,明确告知TypeScript该属性不会为undefined:
<!-- app.component.html --> <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedulerConfig.columns!" [startDate] = "schedulerConfig.startDate!" [endDate] = "schedulerConfig.endDate!" ></bryntum-scheduler>
方案3:强制确保columns存在
在组件中初始化配置时,兜底处理columns为空的情况:
// app.component.ts schedulerConfig = { ...schedulerConfig, columns: schedulerConfig.columns || [] };
或者在配置文件中通过类型断言约束columns必存在:
// app.config.ts import { SchedulerConfig } from '@bryntum/scheduler'; export const schedulerConfig: Partial<SchedulerConfig> & { columns: NonNullable<Partial<SchedulerConfig>['columns']> } = { columns : [ { text : 'Name', field : 'name', width : 160 } ], startDate : new Date(2022, 10, 17), endDate : new Date(2022, 10, 23) };
内容的提问来源于stack exchange,提问作者BennoDual
相关产品推荐
相关产品推荐

