ReactJS - TypeScript 기초

컴업·2022년 12월 22일
0

TypeScript 특징

  • Javascript기반 프로그래밍 언어.

  • Strongly-type하다.
    : 모든 Data에 Type을 지정한다. 다시말해 프로그래밍 언어가 작동하기 전, Data의 Type을 확인한다.

[JavaScript]
const plus = (a, b) => a + b;

console.log(plus(1, 3)); <<<--- 4
console.log(plus(1, 'hello'));  <<<--- 1hello
- a와 b가 number type임을 보장하지 않는다.
[TypeScript]
const plus = (a:number, b:number) => a + b;

console.log(plus(1, 3)); <<<--- 4
console.log(plus(1, 'hello'));  <<<--- 에러 발생
- a와 b가 number type임을 보장한다.
  • 객체 모양에 따라 타입을 생성한다.
    - Javascript에서는 아래 생성한 book과 food의 데이터 타입을 모두 Object 타입이지만, TypeScript에서는 이를 book 타입, food 타입으로 각각 인식한다.

const book = {
  title: "toystroy",
  description: "A story that toys do something",
}

const food = {
  name: "tomato",
  color: "red",
}
  • 타입을 지정함으로서 코드를 실행하지 않아도 아래와 같이 데이터 형태의 유효성을 검증할 수 있다.
[JavaScript]
const user = {
	firstName: "Angela",
    lastName: "Davis",
    role: "Professor"
};

console.log(user.name); <<<--- undefined.
[TypeScript]
const user = {
	firstName: "Angela",
    lastName: "Davis",
    role: "Professor"
};

console.log(user.name); <<<--- user.name은 정의되지 않았으므로 에러발생.

CRA에 TypeScript 설치


npx create-react-app app-name --template typescript

# or

yarn create-react-app app-name --template typescript

Document

라이브러리 설치

javascript로 만들어진 라이브러리를 사용하기 위해서 아래와 같은 명령어로 추가 설치한다.

npm i @types/library-name

@types : DefinitelyTyped 이라는 거대 깃허브로, 많은 사람들이 npm에 존재하는 유명 라이브러리를 TypeScript로 사용할 수 있도록 개발하고있다. (각 라이브러리의 객체들을 Type으로 만들어둔 것.)

interface

: 특정한 Object shape(객체 모양)을 number와 같은 Data Type으로 정의하는 TypeScript의 개념.

  • PropType과 유사하지만 코드를 실행해야 에러를 알 수 있는 PropType과 달리, 코드 실행 전에 에러를 확인할 수 있다.

  • interface에 object shape을 설정해두고, Component가 받는 props에 interface에 설정해둔 object Type을 지정해준다.

import styled from "styled-components"

const Container = styled.div<CircleProps>`   <<<--- styled-components가 interface를 받는 방식
  width: 100px;
  height: 120px;
  background-color: ${props => props.bgColor};
`;  

interface CircleProps {
  bgColor: string;
}

function Circle({bgColor}: CircleProps) {  <<<--- Components가 받는 방식
  return <Container bgColor={bgColor}/>;
}

export default Circle;

위 코드에서 Circle Component가 받는 props는 data 타입이 CircleProps type이어야 한다.

1) optional props

interface를 통해 생성한 type의 인자들중 없을 수 있는 인자들은 "?"를 이용해 Optional 상태로 설정할 수 있다.

interface BookPorps {
  title: string;
  author: string;
  pages: number;
  coverImgUrl?: string; <<<--- string | undefined 와 같은 뜻.
  descrition?: string;
}

위 BookPorps type인 객체들은 string 타입인 title, author 그리고 number 타입인 pages를 꼭 가지고 있어야하지만 coverImgUrl, description은 갖지 않아도 괜찮다.

2) default

타입 인자가 undefined일 경우 default 값을 지정할 수 있다.
- TypeScript 기능은 아니고 JavaScript에서 제공하는 기능이다.

function Book({
  title,
  author,
  pages,
  coverImgUrl,
  description = "default 책설명",     <<<--- default값 설정가능
}: BookPorps) {
  return (
    <Container title={title} author={author} pages={pages}
      coverImgUrl={coverImgUrl ?? "http://img.com/222"}
    >
      {description}
    </Container>
  );
}

React State 처리

  • useState<type>(); 를 통해 state의 type을 지정할 수 있다.
const [value, setValue] = useState<number|string>(1);

value 의 타입은 number 혹은 string.

  • 따로 설정하지 않았다면, 초기 설정값의 type이 지정된다.
const [value, setValue] = useState(1);

위코드에서 초기값 1의 type은 number임으로 value state의 type은 앞으로 number로 지정된다.

React Forms 처리

React에서 HTML input 태그를 처리하는데 아래와 같은 코드를 사용하게된다.

onChange 메서드에서 event를 받을 때, 이 event의 interface를 생성할 수 는 없다.

때문에 React에서 제공하는 type React.FormEvent<HTMLInputElement>을 받아 사용하게된다.

이와 같이 React에서 제공하는 type을 사용해야하는 경우 구글링 혹은 document를 참고하자.

import { useState } from "react";

function App() {
  const [value, setValue] = useState("");
  const onChange = (event: React.FormEvent<HTMLInputElement>) => {  <<<---
    setValue(event.currentTarget.value);
  }
  return <div>
    <form>
      <input value={value} onChange={onChange} type="text" placeholder="username" />
      <button>Log in</button>
    </form>
  </div>;
}

export default App;

Document

TypeScript에서 styled-components theme 사용하기

Document

1) 설치

npm install --save-dev @types/styled-components

2) declarations 파일 생성

내가 사용할 theme 객체의 type은 declarations 파일을 생성해 정의한다. (styled.d.ts)

[styled.d.ts]

import 'styled-components';

declare module 'styled-components' {
  export interface DefaultTheme {
    textColor: string;
    bgColor: string;
  }
}

theme type에 맞춰 theme를 생성한다. (theme.tx)

import { DefaultTheme } from "styled-components";

export const lightTheme: DefaultTheme = {
  bgColor: "white",
  textColor: "black",
  btnColor: "tomato",
};

export const darkTheme: DefaultTheme = {
  bgColor: "black",
  textColor: "white",
  btnColor: "teal",
};

아래 코드와 같이 index.tx에 theme를 세팅 한 후

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(
  <React.StrictMode>
    <ThemeProvider theme={darkTheme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>
);

'props.theme.지정한색'으로 사용 가능하다.

const TitleMsg = styled.h1`
  color: ${props => props.theme.textColor};
`;

profile
좋은 사람, 좋은 개발자 (되는중.. :D)

0개의 댓글