28
loading...
This website collects cookies to deliver better user experience
function returnWhatItGets<Type>(arg: Type): Type => arg;
< Type>
tells typescript that when we use this function, we will be able to insert a dynamic type that will serve as the Type of our argument (arg
) and the Type of the return value of this function.const numberOutput = returnWhatItGets<number>(5);
const stringOutput = returnWhatItGets<string>("hi");
1 import React from 'react';
2
3 export type GenericComponentProps<Type> = {
4 data: Type[];
5 };
6
7 export function GenericComponent<Type>({ data }: 8GenericComponentProps<Type>) {
9 return (
10 <>
11 {data?.map((item: Type, index: number) => (
12 <ul key={index}>
13 {(Object.keys(data[0]) as Array<keyof Type>).map((key) => (
14 <li key={key.toString()}>{item[key]}</li>
15 ))}
16 </ul>
17 ))}
</>
);
}
<ul>
attribute.<GenericComponent
data={[
{ name: 'Nitsan', city: 'Harish' },
{ name: 'Abraham', city: 'Beer Sheva' },
]}
/>
For more posts like this follow me on LinkedIn
I work as frontend & content developer for Bit - a toolchain for component-driven development (Forget monolithic apps and distribute to component-driven software).