0

This file returns edges either as an array of objects or a singular object.

However, TypeScript doesn't accept my attempts at suggesting it could be an array or not.

As it is here, it errors on the map function - if I set edges in CategoriesProps to an array, then it errors on categories.edges.node.name

Any ideas on how to progress?

Thanks

type CategoriesProps = {
  categories: {
    edges: {
      length: number;
      node: {
        name: string;
      };
    };
  };
};

export default function Categories({ categories }: CategoriesProps) {
  return (
    <span className="ml-1">
      under
      {categories.edges.length > 0 ? (
        categories.edges.map((category, index) => (
          <span key={index} className="ml-1">
            {category.node.name}
          </span>
        ))
      ) : (
        <span className="ml-1">{categories.edges.node.name}</span>
      )}
    </span>
  );
}

1 Answer 1

1

Change your check to Array.isArray:

type Edge = {
  length: number;
  node: {
    name: string;
  };
};

type CategoriesProps = {
  categories: {
    edges: Edge | Edge[];
  };
};

export default function Categories({ categories }: CategoriesProps) {
  return (
    <span className="ml-1">
      under
      {Array.isArray(categories.edges) ? (
        categories.edges.map((category, index) => (
          <span key={index} className="ml-1">
            {category.node.name}
          </span>
        ))
      ) : (
        <span className="ml-1">{categories.edges.node.name}</span>
      )}
    </span>
  );
}

This is how you should be checking for arrays in JavaScript anyways.

Sign up to request clarification or add additional context in comments.

1 Comment

Much appreciated...this does as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.