Practicing Typescript: Restricting props

zenoan·2021년 12월 21일
0

typescript

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

Restricting props

// App.tsx
import { RandomNumber } from './components/restriction/RandomNumber'

function App() {

	return (
    	<div className='App'>
        {/* Can also be set as isNegative and isZero */}
        	<RandomNumber value={10} isPositive />
        </div>
    )
}
type RandomNumberType = {
  value: number
}
// Use of & to specify restrictions
// Never type: Ex) When isPositive isNegative and isZero cannot be set or used together
type PositiveNumber = RandomNumberType & {
  isPositive: boolean
  isNegative?: never
  isZero?: never
}

type NegativeNumber = RandomNumberType & {
  isNegative: boolean
  isPositive?: never
  isZero?: never
}

type Zero = RandomNumberType & {
  isZero: boolean
  isPositive?: never
  isNegative?: never
}

type RandomNumberProps = PositiveNumber | NegativeNumber | Zero

export const RandomNumber = ({
  value,
  isPositive,
  isNegative,
  isZero
}: RandomNumberProps) => {
  return (
    <div>
      {value} {isPositive && 'positive'} {isNegative && 'negative'}{' '}
      {isZero && 'zero'}
    </div>
  )
}
profile
프론트엔드 개발자
post-custom-banner

0개의 댓글