Home > Software engineering >  How to type this react function with nested / mapped objects?
How to type this react function with nested / mapped objects?

Time:12-15

I'm new to Typescript and can't figure out how to properly type the following. I've tried using Interface in various manifestations, as well as individually typing properties or a combination of the two, but this only get me so far and seems to raise new typing errors.

I think part of the issue is typing the map function and properties within it such as the nested objects/values.. how best to do this?

export function Navigation( { navigation } ) {

    return (
      <nav>
        <ul>
      
          {navigation.data.slices.map( ( slice ) => {
            return (
              <li key={slice.id}>
                <PrismicLink field={slice.primary.menu_item_link}>
                  {slice.primary.menu_item_label}
                </PrismicLink>
              </li>
            )
          })}
        </ul>
      </nav>
    )

}

CodePudding user response:

You'll want object types (defined via type or interface) for the various objects in your props, such as data, the values in the slices array, and the values of their primary property. For instance, something like:

interface Something {
    menu_item_link: string;
    menu_item_label: string;
}
interface Slice {
    id: string; // Or `number` or whatever
    primary: Something;
}
interface NavigationData {
    slices: Slice[];
}

Then your props interface is an object with a navigation property:

interface NavigationProps {
    navigation: {
        data: NavigationData;
    };
}

And you use it by defining the type of the props your function accepts:

export function Navigation({ navigation }: NavigationProps) {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^
    return // ...
}

TypeScript playground link

I should note that the division of the object types above is a matter of taste and probably varies a bit depending on domain knowledge. It's entirely possible to define all of the above with just NavigationProps, but it's probably not ideal (example).

  • Related