Answer the question
In order to leave comments, you need to log in
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
Generic type 'Props<T>' requires 1 type argument(s)
Answer the question
In order to leave comments, you need to log in
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
Propsfunction list<T>(props: Props<T>):
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question