No index signature with a parameter of type 'string' was found on type '{ home: boolean; profile: boolean; }'.ts(7053)
- type script에서는 객체를 순회할때 string type의 key를 허용하지 않는다고 한다.
- string 타입이 아니라 정확한 키의 값이 일치해야 하는 것 같다.
// str에서 string 타입을 추론 할 수 있다. 또한 let으로 변경 가능 하고 str은 string 타입이 라는 것이 더욱 강해진다고 생각하면 될듯. let str = 'changeable'; // 반면에 str2는 string 이지만 'unchangeable'으로 고정되어 있다. const str2 = 'unchangeable'; // 스트링 리터럴
실제 사용했던 코드를 보자
const initialState: StateType = { home: true, profile: false, } type DirType = 'home' | 'profile'; // 이런식으로 index signature 타입을 선언해 주지 않으면 에러가 발생한다. // type StateKeyType = {[key: string]: boolean;} // StateType 대신 StateKetType을 줘야 함. const changeDir = (state: StateType, type: DirType) => { const newState = { ...state }; for(const key in newState) { // 여기서 부터 에러 발생한다. if(key === type) newState[key] = true; else newState[key] = false; } return newState; }
Argument of type 'string' is not assignable to parameter of type 'DirType'
요 친구는 액션 리듀서에서 action.payload에서 발생 하였다.
앞의 에러를 바탕으로 액션생성함수의 payload값을 as const로 고정시켜 해결 하였다.export const goHome = () => ({ type: GO_HOME, payload: 'home' as const });