TIL 20220513 타입의 property에 null 추가하기(feat: utility type)

jiffydev·2022년 5월 13일
0

문제상황

아래와 같이 정의된 MessageProps 타입이 있다.

type MessageProps = {
	name: string
  	phone: string
  	...
}

그런데 phone property에 null이 존재하는 경우가 있어 이를 해결해야 한다.
다만 MessageProps 타입의 phone은 반드시 string이어야 하므로 타입을 직접 수정해서는 안되고, 새로 타입을 생성해야 한다.

해결

첫 번째 시도

https://stackoverflow.com/questions/43159887/make-a-single-property-optional-in-typescript
위 글을 보고 새로 Optional이라는 타입을 정의해 보았다.

type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
type UncertainMessageProps = Optional<MessageProps, 'phone'>

const messageProps:UncertainMessageProps={
    name:'John Doe',
    phone:null
}

phone에는 null 아니면 전화번호(string)이 들어가야 하는데, 위 코드를 입력해보면
Type 'null' is not assignable to type 'string | undefined' 이라는 메시지가 나오면서 에러가 발생한다.

두 번째 시도

phone property를 우선 제거하고 새로 null이 가능한 타입을 추가시키는 방법이 있다.

type UncertainMessageProps = Omit<MessageProps, 'phone'> & {phone: string | null}

const messageProps:UncertainMessageProps={
    name:'John Doe',
    phone:null
}

이렇게 하니 null도 정의할 수 있게 되어 에러가 발생하지 않는다.

profile
잘 & 열심히 살고싶은 개발자

0개의 댓글