Home > Enterprise >  Typescript React conditional type check type and foreach on array
Typescript React conditional type check type and foreach on array

Time:10-31

Given the following class:

export class condition {
    attribute: string;
    operator: string;
    value: (string | any[]);
    uitype: string;
    valueof: string;
    operationTypeAttributeTypeCode: AttributeTypeCode;
    attributeValueHistory: attributeValueHistory[];
}

for the value field, I want to determine if the type is of type any[] and if it is, peform a forEach on the array values

I have tried type casting such as (obj.value as any[]) != undefined or .length > 0 but cant ever seem to test for the type correctly.

Is there a reliable way to do this?

Thank you

CodePudding user response:

Just use regular Array.isArray check, like here:

export class Condition {
    attribute: string;
    operator: string;
    value: (string | any[]);
    uitype: string;
    valueof: string;
    operationTypeAttributeTypeCode: AttributeTypeCode;
    attributeValueHistory: attributeValueHistory[];
}

const instance = new Condition();

if (Array.isArray(instance.value)) {
    instance.value.forEach(console.log)
}
  • Related