Home > database >  TypeScript: How to make sure two props of a functional component, which are arrays, have the same le
TypeScript: How to make sure two props of a functional component, which are arrays, have the same le

Time:10-10

I'm trying to make a functional component in react which accepts two separate strings as props. Is there a way to make sure that these two arrays must have the same length, using TypeScript? In other words, when we are using this component inside other components, unless the props are the same length, we will receive an error.

To give you a simple example, imagine something like this:

export const TableView = ({ s1, s2 }: { s1: string[]; s2: string[] }) => {
  return (
    <table>
      <thead>
        <tr>
          {s1.map((s, index) => {
            return <th>{s1[index]}</th>;
          })}
        </tr>
      </thead>
      <tbody>
        <tr>
          {s2.map((s, index) => {
            return <td>{s2[index]}</td>;
          })}
        </tr>
      </tbody>
    </table>
  );
};

I want to make sure I see an error when I use it with strings having different length.

      <TableView s1={["1", "2", "3"]} s2={["1", "2", "3", "4"]} />
      {/* show an error here */}


CodePudding user response:

You can simply put the condition in your jsx like so :

export const TableView = ({ s1, s2 }: { s1: string[]; s2: string[] }) => {
  return (
  {s1.length === s2.length ?
    <table>
      <thead>
        <tr>
          {s1.map((s, index) => {
            return <th>{s1[index]}</th>;
          })}
        </tr>
      </thead>
      <tbody>
        <tr>
          {s2.map((s, index) => {
            return <td>{s2[index]}</td>;
          })}
        </tr>
      </tbody>
    </table>
   :
   <p> Error arrays are not the same length ...</p>
   }
  );
};

CodePudding user response:

I think you can use something like below before return

if(sl.length !== s2.length) {
  throw "Arrays are of different length"; //which throws custom exception
 /*Or you can return anything that suits your needs*/
}
return(
  //here goes your code
)
  • Related