2022-02-26 TIL {state, event}에 type 지정, 새롭게 알게된 ES6문법

Romuru·2022년 2월 26일
0

TIL

목록 보기
3/10

state를 type 지정

state를 typescript로 타입 지정을 할때는 기본값으로 설정이된다

cosnt [color, setColor] = useState("blue");

일때 따로 지정을 안해줘도


setColor(123);
setColor("skyblue");
setColor(true);

2번째 setColor만 정상적으로 실행된다.

대부분의 경우에서 state는 한 타입으로 되는경우가 많기 때문에 지정해줄일이 거의 없지만

그래도 따로 지정을 한다면

cosnt [color, setColor] = useState<String|number>("blue");

로 코드를 작성하면

setColor(123);
setColor("skyblue");
setColor(true);

1,2번째 setColor들이 정상 작동한다.

event를 타입지정

const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log("hello",value);
  };

event 기본 타입이 any로 지정 되어서 그냥 사용할수있지만 그냥 사용 하게 되면

typescript를 사용하는 의미가 줄어든다 .

event: React.FormEvent 로 지정해줄수있지만

되게 낯선 개념이라 몇번더 사용해서 익어야 할꺼같다.

그리고 ES6문법에서 새롭게 알게된 문법은

const{
      currentTarget: {value}
    } = event;

인데 의미는 event.currentTarget.value 에서 value 의 이름으로 새로운 변수를 선언하는 것이다.

const value = event.currentTarget.value; 와 같은 의미이다.

const value = event.currentTarget.value;
const userName  = event.currentTarget.userName;
const age = event.currentTarget.age;

에서

const {
currentTarget: {value, userName, age}
} = event;

로 간단하게 줄여쓸 수 있다.

profile
늘 새로운 호기심을 찾고, 기술적 한계에 도전하고, 하늘색이 잘 어울리는 사람입니다.

0개의 댓글