[英]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.