【发布时间】:2022-11-15 13:28:15
【问题描述】:
** 我的问题与角度 @Input () 装饰器有关,因为当我使用此装饰器时,打字稿抛出错误,而不是在常规代码中使用时。
在我的 child.component.ts 文件中,我声明这个装饰器从父组件获取道具:
@Input() customColumns: {
name: string;
index: number;
type: 'icon' | 'image' | 'link' | 'button';
icon?: any;
url?: string;
}[] = [];
indexList: number[] = [];
在我的 parent.component.ts 文件中,我正在为这个变量分配值,如下所示:-
customColumns = [
{ name: 'permissions', index: 7, type: 'icon', icon: faSave },
{ name: 'price list', index: 6, type: 'link', icon: faArrowDownWideShort },
{ name: 'details', index: 5, type: 'button', icon: faArrowUpWideShort },
];
最后,在我的 parent.component.html 文件中,我调用了该子组件:-
<app-child [customColumns]="customColumns">
</app-child>
但得到这个错误: -
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"button" | "link" | "image" | "icon"'.
但是当我在正常的打字稿或 ngOnInit() 函数中做同样的事情时,它正在工作,无法弄清楚为什么会发生,请帮助我,在此先感谢。
let customColumns: {
name: string;
index: number;
type: 'icon' | 'image' | 'link' | 'button';
icon?: any;
url?: string;
}[] = [];
customColumns = [
{ name: 'permissions', index: 7, type: 'link', icon: '' },
{
name: 'price list',
index: 6,
type: 'icon',
icon: faArrowDownWideShort,
},
{ name: 'details', index: 5, type: 'icon', icon: faArrowUpWideShort },
];
我的项目依赖项:
"@angular/cli": "~14.2.7", "typescript": "~4.7.2"
【问题讨论】:
-
你可以设置 type?:any
-
我可以,但我想限制一下,其他人只能分配 4 个选项或字符串值。
标签: angular typescript