I have a data type:
export interface TYPE_A {
valueType: TYPE_A_VALUE_TYPES;
value: string | string[];
}
export enum TYPE_A_VALUE_TYPES {
singleValue = "singleValue",
multiValue = "multiValue",
}
And, I using TYPE_A
in the component for @Input
:
@Input() datas: TYPE_A[] = [];
And this is my HTML code:
<div class="feildContainer" *ngFor="let data of datas">
<div class="singleFeild" *ngIf="data.valueType == 'singleValue'">
...
</div>
<div class="multiFeild" *ngIf="data.valueType == 'multiValue'">
<other-component *ngFor="let dataValue of data.value"></other-component>
<div>
</div>
I getting this error in vscode
:
NgForOf<string | string[], NgIterable<string | string[]>>.ngForOf: NgIterable<string | string[]> | null | undefined
I understand the logic of this error, But I'm looking for the best solution to this problem.
Use a discriminated union as your type:
export interface TYPE_A_SINGLEVALUE {
valueType: TYPE_A_VALUE_TYPES.singleValue;
value: string;
}
export interface TYPE_A_MULTIVALUE {
valueType: TYPE_A_VALUE_TYPES.multiValue;
value: string[];
}
export enum TYPE_A_VALUE_TYPES {
singleValue = "singleValue",
multiValue = "multiValue",
}
Then, when you want to use the value
item, you first check the valueType
against one of the two possible values, and the compiler will know that you want to refer to either the single or multivalued item and assume accordingly. After an if
of valueType
value
won't be string | string[]
, but string
or string[]
as checked.