Typescript-React: Generic key when looping through array of objects defined in a props interface

Viewed 546

I created an "InfoList" component in React where I want to pass through an array of objects as props then map out the results in a list-type format, the only trouble is the array is fetched from an API and the keys will have different names depending on the specific URL passed to the API. I feel as though generics are the answer here and have tried that approach but keep getting syntax errors

interface IInfoList {
title: string;
arr: {
    //want the key here to be generic 
    key: string;
}[]; }

export const InfoList = (props: IInfoList) => {
return (
    <Row className="align-items-start">
        <Col lg={1}>
            <h5>{props.title}:</h5>
        </Col>
        <Col>
            {props.arr.slice(0, 6).map((item, i) => {
                //Generic key accessed via "item" here
                return <p className="pr-1 mb-0 d-inline" key={i}>{`${item.key}, `}</p>;
            })}
        </Col>
    </Row>
); };

I'm new to typescript and the concept of generics, so apologies if this is painfully obvious, but does anyone have any ideas?

1 Answers

It can be like this:

interface IInfoList<T> {
  title: string;
  arr: {
    //want the key here to be generic
    key: T;
  }[];
}

// extends unknown it's a hack to make the linter happy
export const InfoList = <T extends unknown>(props: IInfoList<T>) => {
  return (
    <Row className="align-items-start">
      <Col lg={1}>
        <h5>{props.title}: </h5>
      </Col>
      <Col>
        {props.arr.slice(0, 6).map((item, i) => {
          //Generic key accessed via "item" here
          return (
            <p className="pr-1 mb-0 d-inline" key={i}>
              {' '}
              {`${item.key}, `}
            </p>
          );
        })}
      </Col>
    </Row>
  );
};

Then usage

const Parent = () => {
  return (
    <>
      <InfoList<number>
        title="Title"
        arr={[
          {
            key: 1,
          },
        ]}
      />
      <InfoList<string>
        title="Title"
        arr={[
          {
            key: '1',
          },
        ]}
      />
    </>
  );
};
Related