'How to type a map function that receives different types of arrays?

I have created the following function and I need to type the i argument that is currently an any:

  1. scenario - with value and label

enter image description here

  1. scenario - with id and name

enter image description here

  1. scenario - without extra properties enter image description here

And my main problem is that I can receive an array that has different property names, like:

const status: {
    status: number;
    label: string;
}[],
const departments: {
    id: number;
    name: string;
}[]

so my i sometimes can be status and label but can also be id and name. So how to properly type this i? I tried using unknown but I get this message:

enter image description here



Solution 1:[1]

Try set i to both types instead of any:

const handleMap = (arr: Array<unknown>, filterValue?: string, filterLabel?: string) => {
    return arr
        ? arr.map((i: status | departments) => ({
                value: i.toString(),
                label: i,
          }))
        : [];
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Majid M.