Practicing Typescript: Generic props

zenoan·2021년 12월 21일
0

typescript

목록 보기
6/11

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>
    )
}
profile
프론트엔드 개발자

0개의 댓글