function changeToAuth(e: ChangeEvent<HTMLInputElement>) {
const { name, value } = e.currentTarget;
const next = produce(state, (draft: State) => {
if (name === 'check') {
const idx = draft.agree.indexOf(+value);
if (idx > -1) {
draft.agree.splice(idx, 1);
} else {
draft.agree.push(+value);
}
} else {
draft[name] = +value; //여기서 draft[name] 오류가 남!!!
}
});
setState(next);
}
자바스크립트는 key type(number, string, symbol)을 이용해서 동적으로
object에 프로퍼티가 가능! 무슨 말이냐.
const person1 = {};
person1['name'] = '은지';
person1['age'] = 2
console.log(person1); // {name: '은지', age: 2}
하지만 타입스크립트는 key type이 일단 string number만 가능하고
key type을 오브젝트가 동적으로 받을건지 정해줘야한다!!
해결방안
interface에 [key: string]: number | string;
추가 해주자!
[참조]: https://velog.io/@dongdong98/index-Signature-동적으로-Object에-property-추가하기
이메일 / 비밀번호와 체크박스를 하나의 함수로 사용하고 있었다.
애초에 안되는게 체크박스는 배열이고 이메일 비밀번호는 그냥 string
이런건 함수를 나눠줘야 편하다!
근데 이렇게 해도 draft[name] = value
여전히 오류가 난다
// 1. 인터페이스에 삽입 / 이때 any로 넣어주고
interface Prop {
[key: string]: any,
}
// 2. 여기와서 좁혀주기!
function changeToAuth(e: ChangeEvent<HTMLInputElement>) {
const { name, value } = e.currentTarget;
const next = produce(state, draft => {
draft[name as keyof string] = value;
});
setState(next);
}
// 여기서 의문은 [key: string]: string 하면 안되나? 생각할 수 있음
// 하지만 저거 하려면 Prop에 들어있는 다른 타입도 다 string이여야 가능한거임!!