H
H
Hazrat Hajikerimov2019-06-14 17:28:40
typescript
Hazrat Hajikerimov, 2019-06-14 17:28:40

TypeScript Generics: Reusable component?

Hello, just started to get acquainted with TypeScript.
I want to write a reusable component so that, depending on the type passed, it renders a list.
Generics are suitable for this task, here is what I got, but does not work:

interface Project {
  id: number,
  title: string,
  date: string
}

interface Education {
  id: number,
  title: string
}

interface Props<T> {
  items: T[],
  render: (items: T[]) => JSX.Element[]
}

const project: Project[] = [
  { id: 1, title: '1', date: '20.05.2017' },
  { id: 2, title: '2', date: '21.05.2017' }
]

const education: Education[] = [
  { id: 1, title: '1' },
  { id: 2, title: '2' }
]

function list<T extends Props>(props: T): JSX.Element {
  return (
    <div>
      {props.render(props.items)}
    </div>
  )
}

const renderProject = list<Props>({
  items: project,
  render: (items: Project[]) => items.map((item: Project) => <span>{item.title}</span>)
})

const renderEducation = list<Props>({
  items: education,
  render: (items: Education[]) => items.map((item: Education) => <span>{item.title}</span>)
})


export default list

The logic is this, there are 2 interfaces Project and Education, there are 2 arrays that implement these interfaces.
Then there is the Props interface, where the generic for items is used, there we will pass arrays based on Project and Education, as well as the render method, which receives the same array and renders it.
Accordingly, the implementation of this interface in the list method, where T extends Props, which causes an error:
Generic type 'Props<T>' requires 1 type argument(s)

Just below 2 renderProject and renderEducation methods that execute the list method with the required types, but do not work (
help me figure it out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-06-14
@hazratgs

As stated in the error - Props is a generic, and you can’t write <T extends Props>, you need to write <T extends Props<Something>>
to list you don’t need to pass Props, you need to pass T to it, which is already used inside to pass something like this to
Props
function list<T>(props: Props<T>):

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question