By implementing type guards, Typescript has the ability to narrow down a union type effectively. Utilizing a narrowing condition is simple enough, but integrating a type guard function enhances reusability and flexibility:
function isAnyArray(value: any[] | string): value is any[] {
return value instanceof any[];
}
This allows you to carry out your assignment as usual and then operate within the scope provided by your type guard:
let obj: string | any[] = test();
if (isAnyArray(obj)) {
//Utilize obj here as if it were an any[]
}
Given that your union is utilized in multiple instances, consider defining a type for it and using it instead of the manual union type:
type StringOrAnyArray = string | any[];
//...
function isAnyArray(value: StringOrAnyArray): value is any[] {
return value instanceof any[];
}
//...
let obj: StringOrAnyArray = test();
if (isAnyArray(obj)) {
//Utilize obj here as if it were an any[]
}