Created
August 28, 2022 14:20
-
-
Save pingan8787/1f58135c1a25db0b5c4de08ffed9605d to your computer and use it in GitHub Desktop.
Generic Components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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