Practicing Typescript: Basic Props

zenoan·2021년 10월 27일
0

typescript

목록 보기
1/11
post-custom-banner

  • Provides static type checking and get to learn about potential bugs as one is typing the code without the need to detect the bugs at runtime.
  • Provides a way to describe the shape of an object and therefore provide better documentation and autocompletion.
  • Provides maintenance and refactoring easier when it comes to large code bases.

Props

Basic props

// App.tsx
import { Greet } from './components/Greet'
import { Person } from './components/Person'
import { PersonList } from './components/PersonList'

function App() {
  const personName = {
  	first: 'Bruce',
    last: 'Wayne',
  }
  const nameList = {
    {
     first: 'Bruce',
     last: 'Wayne',
  	},
    {
     first: 'Jay',
     last: 'Lays',
  	},
    {
     first: 'Clark',
     last: 'Kent',
  	},
  }
	return (
    	<div className='App'>
        	<Greet name='John' messageCount={10} isLoggedIn={true} />
        	<Person name={personName} />
        </div>
    )
}

String / number / boolean

// Greet.tsx
type GreetProps = {
  name: string
  messageCount: number
  isLoggedIn: boolean
}

export const Greet = (props: GreetProps) => {
  return (
    <div>
      {props.isLoggedIn ? (
        <h2>
          Hey {props.name}! You have {messageCount} unread messages
        </h2>
      ) : (
        <h2>Welcome Guest</h2>
      )}
    </div>
  )
}

Object

// Person.tsx
import { PersonProps } from './Person.types'

export const Person = (props: PersonProps) => {
  return (
    <h2>
      {props.name.first} {props.name.last}
    </h2>
  )
}
// Person.types.ts
export type Name = {
  first: string
  last: string
}
export type PersonProps = {
  name: Name
}

Array

//PersonList.tsx
import { Name } from './Person.types'

type PersonListProps = {
  names: Name[]
}

export const PersonList = (props: PersonListProps) => {
  return (
    <div>
      {props.names.map(name => {
        return (
          <h2 key={name.first}>
            {name.first} {name.last}
          </h2>
        )
      })}
    </div>
  )
}
// Person.types.ts
export type Name = {
  first: string
  last: string
}
export type PersonProps = {
  name: Name
}
profile
프론트엔드 개발자
post-custom-banner

0개의 댓글