void 함수 타이핑의 특징을 알게 되는 과정

gongyoon·2023년 12월 19일
0

typescript

목록 보기
2/2
post-thumbnail

zustand의 기본 코드를 보다 javascript, typescript의 특징이라고 생각 되는 부분에서 이해가 잘 되지 않는 것이
생겨 구글링과 커뮤니티 질문을 통해 해결할 수 있었다.

import {create} from 'zustand'

interface CountState {

counts: number;

increaseCount: () => void;

}

const useCountState = create<CountState>((set) => ({

counts: 0;

increaseCount: () => set(state => ({ counts: state.counts +1 })),

}));

내가 이해한 바로는 set(state => ({ counts: state.counts +1 }))가 return 이 생략된 concise body 형태로 보이는데
interface에서 타입은 void로 명시되어있어서 의문이 들었고 새롭게 알게된 점은 아래와 같다.

  • void는 반환되는 것이 없다는 의미이나 실제로 반환되는 값은 undefined이다.
  • void 함수 타이핑은 반환하는 것을 강제하지 않는다. 다만 함수의 실제 반환된 값은 무시한다.

이런 특징으로 아래와 같은 작성이 가능하다.

type voidFunc = () => void

const f1: voidFunc = () => {
  return true
}

const f2: voidFunc = () => true

const f3: voidFunc = function () {
  return true
}

console.log(f1()) // undefined
console.log(f2()) // undefined
console.log(f3()) // undefined
profile
공부하며 성장하는 사람이 되고 싶은 개발자.

0개의 댓글