Switch
문 안에서let
,const
키워드
TypeScript로 마이그레이션 중 Redux
를 사용하여 상태관리를 한 코드에서
Switch
문을 작성중에 Lexical Scope 오류가 발생했다.
let, const는 변수를 블록 스코프로 가지는 지역변수로 만들어주는데, Switch 안에 case 문에서
별도의 Lexical Scope 가 없기 때문에 코드오류가 발생했다.
변수와 함수의 유효범위를 결정하는 방법 중 하나를 얘기한다. 코드를 작성할 때 변수와 함수가 어디서 접근 가능한지를 결정한다.
case 'ROLL_DICE':
const nextMyNum = random(6)
const nextOtherNum = random(6)
const myNewHistory = [...state.myHistory, nextMyNum]
const otherNewHistory = [...state.otherHistory, nextOtherNum]
const newState = {
...state,
myHistory: myNewHistory,
otherHistory: otherNewHistory,
}
return calculateWinner(newState)
위 코드는 내가 작성한 코드 중 일부를 가져왔다. case
문에서 const로 지정한 변수들이 존재하여 기존 case 문 안에서는 별도의 렉시컬 스코프가 없기에 코드에 오류가 나온다.
case 'ROLL_DICE': {
const nextMyNum = random(6)
const nextOtherNum = random(6)
const myNewHistory = [...state.myHistory, nextMyNum]
const otherNewHistory = [...state.otherHistory, nextOtherNum]
const newState = {
...state,
myHistory: myNewHistory,
otherHistory: otherNewHistory,
}
return calculateWinner(newState)
}
생각보다 간단하게 해결할 수 있다. 위와 같은 이슈를 해결하기 위해서는 case
문을 {}
감싸면 된다.