简体   繁体   中英

Is it possible to declare generics react functional components using typescript?

What I want is to annotate a generic in one react functional component like this:

import React, {useEffect, useState} from "react";

interface PaginatedTableProps{
  dataFetcher: (pageNumber: number) => Promise<any>,
  columnNames: string[]
}    

export function PaginatedTable<T>(props: PaginatedTableProps): JSX.Element {
  const [data, setData] = useState<T[]>([]);
  ...
}

And then specify concrete type for PaginatedTable functional component in another functional component like this:

import React from "react";
import {PaginatedTable} from "./PaginatedTable";
import api from "../../utils/Api";

export function CompanyTable(): JSX.Element{

  interface ConcreteType{
    name: string,
    country: string,
    city: string,
    address: string,
    zipCode: number,
    status: string
  }

  const getData = (pageNumber: number): Promise<any> => {
    return api().getCompanies(pageNumber);
  }

  return (ConcreteType)<PaginatedTable dataFetcher={getData} columnNames={['name', 'country', 'city']}/>
}

Is it possible to implement? And if yes, then how to do it?

This is a working example of generic annotated functional component.

interface IProps<T> {
  data: T;
}
function Table<T>(props: IProps<T>) {
  return <div>{props.data}</div>
}
export default function App() {
  return (
    <div className="App">
      <Table<number> data={24}/>
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM