![](/img/trans.png)
[英]Type 'null' is not assignable to type 'string'. Angular/TypeScript
[英]When using Angular @Input decorator, Typescript Type 'string' is not assignable to type
我的问题与 Angular @Input()
装饰器有关,因为当我使用此装饰器时,typescript 抛出错误,而不是在常规代码中使用时。
在我的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>
但我收到此错误:
属性“类型”的类型不兼容。
类型“字符串”不可分配给类型“按钮” | “链接” | “图像” | “图标”'。
但是当我在正常的 typescript 或 ngOnInit() function 中做同样的事情时,它正在工作,无法弄清楚为什么会发生,请帮助我,在此先感谢。
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"
为了在正常 TypeScript 中复制相同的行为,您应该使用以下场景:
let customColumns: {
name: string;
index: number;
type: 'icon' | 'image' | 'link' | 'button';
icon?: any;
url?: string;
}[] = [];
const anotherValue = [
{ name: 'permissions', index: 7, type: 'link', icon: '' },
{
name: 'price list',
index: 6,
type: 'icon',
},
{ name: 'details', index: 5, type: 'icon', icon: '' },
];
customColumns = anotherValue;
这类似于 Angular 类型检查代码。
为了解决它,您可以使用预定义的枚举:
const enum ColumnType {
icon = 'icon',
image = 'image',
link = 'link',
button = 'button',
}
let customColumns: {
name: string;
index: number;
type: ColumnType;
icon?: any;
url?: string;
}[] = [];
...
type: ColumnType.link,
或者as const
:
type: 'link' as const
请试试这个
1.像这样创建一个class
export class CustomColumns {
constructor(
public name?: string,
public index?: number,
public type?: 'icon' | 'image' | 'link' | 'button',
public icon?: any,
public url?: string
){}
}
2.在你的子组件中这样使用
@Input() customColumns: CustomColumns;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.