[스터디] #2 TypeScript

ch9eri·2022년 9월 21일
0

TypeScript

js를 기반으로한 프로그래밍 언어 -> type 중시

✨ 특징

strongly-typed : 프로그래밍 언어가 작동하기 전에 type 확인

js

const plus = (a,b) ⇒ a+b;

ts

const plus = (a:number ,b:number) ⇒ a+b;

plus(1,1) → O
plus(”a”,1) → ERROR!

타입이 다르면 경고 표시를 보낸다

✨ interface

타입 설명

문법

interface CirclePrps {
    bgColor: string;
}

적용

import styled from "styled-components";

const Container = styled.div``;

interface CircleProps {
    bgColor: string;
}

function Circle({bgColor}: CircleProps) {
    return <Container />;
}

export default Circle;

props 전달할 수 있다

import styled from "styled-components";

interface CircleProps {
    bgColor: string;
}

interface ContainerProps {
    bgColor: string;
}

const Container = styled.div<ContainerProps>``;

function Circle({bgColor}: CircleProps) {
    return <Container bgColor={bgColor} />;
}

export default Circle;

✨ ?

interface - 선택적 요소

interface CirclePrps {
    bgColor: string;
	borderColor?: string;
}

필수가 아닌 바뀔 수 있는 요소일 때 ?를 사용한다

✨ interface 필수 요소

interface ContainerProps {
    bgColor: string;
    borderColor: string;
}
function Circle({bgColor, borderColor}: CircleProps) {
    return <Container bgColor={bgColor} borderColor={borderColor ?? "white"} />;
}

borderColor={borderColor ?? "white"}

: borderColor가 undefined → white

borderColor={borderColor ?? bgColor}

: borderColor가 undefined → bgColor과 동일하게

✨ state의 타입 자동 유추하기

const [counter, setCounter] = useState(1);
setCounter(1);

→ O

const [counter, setCounter] = useState(1);
setCounter("hello");

→ ERROR!

✨ useState<타입>()

타입 정해주기

const [value, setValue] = useState<number|string>(0);

setValue(1); → O
setValue(”hello”); → O
setValue(true); → ERROR

| : 두가지 타입 모두 가능함
ex. <number|string>

✨ FormEvent

React.FormEvent<element>

const onChange = (event: React.FormEvent) => {};

어떤 종류의 element가 onChange 이벤트를 발생시킬지 특정 가능

🧩 TypeScript 특징

const [value, setValue] = useState('');
  const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    const {
      currentTarget: {value},
    } = event;
    setValue(value);
  };
  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log("hello", value);
  };
profile
잘하자!

0개의 댓글