Home > Net >  How to pass interface/type dynamically to a common react function in typescript
How to pass interface/type dynamically to a common react function in typescript

Time:12-25

I have created a common function to render a table.

Table.tsx


interface Type {
  name: string;
  age: number;
}

interface PropType {
  column: Array<Type>;
}

function Table({ column }: PropType) {
  return null;
}

export default Table;

Now I am using this component for two different pages, User and Product. both user and product page has different data to be rendered on table component

User.tsx

import Table from "./Table";

interface InterfaceUser {
  name: string;
  age: number;
}

const users: Array<InterfaceUser> = [
  {
    name: "John",
    age: 21
  }
];
function User() {
  return <Table column={users} />;
}
export default User;

User.tsx works well as we have created the same interface in table component but when it comes to Product.tsx page, we get errors.

import Table from "./Table";

interface InterfaceProduct {
  title: string;
  age: number;
}

const products: Array<InterfaceProduct> = [
  {
    title: "Product name",
    price: 21
  }
];
function Product() {
  return <Table column={products} />;
}
export default Product;

I am new to typescript, any help would really be appreciated.

CodePudding user response:

You can use Typescript generic type like this:

In Table.tsx:

interface PropType<ColumnsType> {
  column: ColumnsType[];
}

function Table<ColumnType>({ column }: PropType<ColumnType>) {
  return null;
}

in User.tsx:

function User() {
  return <Table<InterfaceUser> column={users} />;
}

in Product.tsx:

function Product() {
  return <Table<InterfaceProduct> column={products} />;
}
  • Related