Skip to content

Instantly share code, notes, and snippets.

@pingan8787
Created August 28, 2022 14:20
Show Gist options
  • Save pingan8787/1f58135c1a25db0b5c4de08ffed9605d to your computer and use it in GitHub Desktop.
Save pingan8787/1f58135c1a25db0b5c4de08ffed9605d to your computer and use it in GitHub Desktop.
Generic Components
interface Props<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
const List = <T extends unknown>(props: Props<T>) => {
const { items, renderItem } = props;
const [state, setState] = React.useState<T[]>([]); // You can use type T in List function scope.
return (
<div>
{items.map(renderItem)}
<button onClick={() => setState(items)}>Clone</button>
{JSON.stringify(state, null, 2)}
</div>
);
};
function App() {
return (
<div className="App">
<List<number>
items={[1, 2]} // type of 'string' inferred
renderItem={(item) => (
<li key={item}>
{/* Error: Property 'toPrecision' does not exist on type 'string'. */}
{item.toPrecision(3)}
</li>
)}
/>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment