具有不同结构的对象的变量类型导致错误 属性'propertyname'不存在



我有这个接口,我使用它作为类型的变量在一个组件

export interface IToolbarConfig 
{
items:
[
{
type?:string,
label?:string,
handler?:Function
} ?,
{
type?:string,
label?:string,
} ?
] 
}

toolbar.component.ts:

@Input() config!: IToolbarConfig;

所以,我试着循环items数组到toolbar.component.html:

<ng-container *ngFor="let item of config?.items">
<ng-container *ngIf="item?.type == 'button'">
<button (click)="item?.handler()">{{ item?.label }}</button> 
</ng-container>
</ng-container>

由于property ">handler"只有当type="button">,编译器给我错误

时才存在属性'handler'不存在类型'{type?: string |未定义;标签吗?: string |未定义;处理程序吗?:功能|未定义的;} |{类型?: string |未定义;标签吗?: string |未定义;}"。

我设法解决修改接口,所以

export interface IToolbarConfig 
{
items:
[
{
type?:string,
label?:string,
handler?:Function
} ?,
{
type?:string,
label?:string,
} ?
] | any   <------added this
}

但我不认为这是最好的做法。有什么建议吗?

改变你的界面

// since handler can be undefined your interface was duplicating objects in the array
export interface IToolbarConfig {
items: Array<{
type?: string
label?: string
handler?: Function
} | undefined>
}

然后,如Rabu所说,调用带有可选链接的方法:

<button (click)="item?.handler?.()">{{ item?.label }}</button>

handler可能是undefined,所以您需要为它添加一个检查。您还可以在函数上使用可选的链接。

<ng-container *ngFor="let item of config?.items">
<ng-container *ngIf="item?.type == 'button'">
<button (click)="item?.handler?.()">{{ item?.label }}</button> 
</ng-container>
</ng-container>

为什么不输入items作为

{ 
type?:string,
label?: string,
handler?:Function,
}[]

您的类型在处理程序上使用?这一事实意味着不需要定义它。这意味着,即使你输入的不是按钮你也没有任何要定义的处理程序,你可以不定义它,typescript不会报错

这个声明现在是有效的

let item: items = [{
type: 'myType',
label: 'myLabel',
}]