Practicing Typescript: Generic props
13220 단어 typescript타입스크립트typescript
Generic props
- Generic props can be considered as parameterized types
// List.tsx accepting only strings
type ListProps = {
items: string[]
onClick: (value: string) => void
}
export const List = ({items, onClick}: ListProps) => {
return (
<div>
<h2>List of items</h2>
{items.map(item => {
return (
<div key={item.id} onClick={() => onClick(item)}>
{item.id}
</div>
)
})}
</div>
)
}
// List.tsx with generics
type ListProps<T> = {
items: T[]
onClick: (value: T) => void
}
// Type T extends a base type `<T extends {}>`
// Now can pass to List component a list of any type
// The following:`<T extends {id: number}>` adds a restriction
// that the object must have an id of number type
export const List = <T extends { id: number }>({
items,
onClick
}: ListProps<T>) => {
return (
<div>
<h2>List of items</h2>
{items.map(item => {
return (
<div key={item.id} onClick={() => onClick(item)}>
{item.id}
</div>
)
})}
</div>
)
}
// App.tsx
import { List } from './components/generics/List'
function App() {
return (
<div className='App'>
<List
items={[
{
id: 1,
first: 'Bruce',
last: 'Wayne'
},
{
id: 2,
first: 'Clark',
last: 'Kent'
},
{
id: 3,
first: 'Princess',
last: 'Diana'
}
]}
onClick={item => console.log(item)}
/>
</div>
)
}
Author And Source
이 문제에 관하여(Practicing Typescript: Generic props), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jha0402/Practicing-Typescript-Generic-props저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)