CODING PRACTICE/Typescript

Typescript__With React(001 -- Basic)

HELLICAT 2023. 8. 25. 18:36
반응형

Typescript

Typescript는 Javascript를 기반으로 한 프로그래밍 언어이다.

서로는 다른 언어이지만 엄청 다른 언어는 아니고 새로운 기능이 몇몇 추가된 언어이다. 그래서 문법도 같다.

//Javascript 일때...

const plus = (a,b) => a+b

plus(1,3)
// console.log(plus(1,3)) === 4

plus(1,"hello")
// console.log(plus(1,"hello")) === "1hello"
// TypeScript

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

plus(1,3)
plus(a,2) => 오류 표시가 나옴
plus("3",2) => 오류 표시가 나옴

Typescript 설치

// React와 함께 사용할경우
npx create-react-app 앱이름 --template typescript

// 기존 문서에 추가할 경우
npm i --save typescript @types/node @types/react @types/react-dom @types/jest


/* 어떤 라이브러리나 패키지는 TypeScript로 만들어진게 아니여서 불만 표시가 있다면 type definition인 
@types/라이브러리이름 을 찾아 설치 하는 방법을 고려해보자*/

Typescript가 React에게 설명하는 방법

기존에는 Prop Types를 사용해 prop이 거기 있는지 없는지를 확인해주었다. 하지만 PropTypes는 브라우저 콘솔에 경고표시를 하고 코드를 실행한 후에만 확인가능했다. 우리는 코드가 실행전 확인하려한다.

//App.tsx
import React from "react";
import styled from "styled-components";
import Circle from "./Circle";

export default function App() {
  return (
    <div>
      <Circle bgColor={"teal"} />
      <Circle bgColor={"tomato"} />
    </div>
  );
}
//Circle.tsx
import styled from "styled-components";

//Container의 div에게 bgColor prop에 대한 type을 알려주는 방법
interface ContainerProps {
  bgColor: string;
}
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
`;

//function Circle의 bgColor의 type을 알려주는 방법
interface CircleProps {
  bgColor: string;
}

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

Optional Props

선택적으로 타입의 유무에 대해 확인하는 방법

interface의 object에 물음표(?)를 달아 선택적으로 확인할 수 있다 

물음표는 ? === type | undefine

??는 null 병합연산자 

??앞에 값이 null이거나 undefined라면 오른쪽 아니면 왼쪽

//App.tsx
import React from "react";
import Circle from "./Circle";

function App() {
  return (
    <div>
      <Circle borderColor="red" bgColor={"teal"} />
      <Circle bgColor={"tomato"} text={"문구가 있으면 이 문구로 바뀜"}/>
    </div>
  );
}

export default App;


//Circle.tsx

import styled from "styled-components";

//Container의 div에게 bgColor prop에 대한 type을 알려주는 방법
interface ContainerProps {
  bgColor: string;
  borderColor?: string;
}
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border: 1px solid ${(props) => props.borderColor};
`;



//function Circle의 bgColor의 type을 알려주는 방법
interface CircleProps {
  bgColor: string;
  borderColor?: string;
  text?: string;
}

export default function Circle({bgColor, borderColor, text= '내용이 없으면 이 문구가 default임'}: CircleProps) {
  return(
   <Container bgColor={bgColor} borderColor={borderColor ?? bgColor} >
     {text}
   </Container>
  )
}

State Type

export default function Circle({bgColor, borderColor}: CircleProps) {
  // typescript가 counter의 type을 number로 자동으로 추론한다.
  const [counter, setCounter] = useState(1);
  // 만약 setCounter를 통해 string 값을 줘야한다면 다음과 같이 작성 하지만 그리 자주 사용은 안됨
  const [counter, setCounter] = useState<number|string>(0);
  return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor} />;
}

Form Type

import React, {useState} from "react";

function App() {
  const [val, setVal] = useState("");
  const onChange = (event: React.FormEvent<HTMLInputElement>) => {
    /** event의 타입을 주기위해서는 위와 같이 작성해야하는데 저것을 찾기 위해서는 어떤곳에서 이벤트가 이루어졌는지 생각해보면 쉽게 다가갈수 있음 혹은
     * 공식문서나 구글링을 통해 찾는 걸 추천함 */
    // console.log(event.currentTarget.value);
    /** 또한 보통 자바스크립트 같은 경우엔 target이라고 작성하는데 타입스크립트와 리액트를 같이 사용하는데 있어서 currentTarget으로 작성해야한다.*/
    const {
      currentTarget: {value},
    } = event;
    setVal(value);
  };

  const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log(val);
  };
  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          value={val}
          onChange={onChange}
          type="text"
          placeholder="UserName"
        />
        <button>Log In</button>
      </form>
    </div>
  );
}

export default App;
728x90