[TIL] TypeScript (2)

JunSung Choi·2020년 2월 22일
1

TypeScript

목록 보기
2/2

이제 TypeScript의 기본 사용방법을 익히고 실제 리액트 프로젝트에서 같이 써보려고 한다.

npx create-react-app ts-react-tutorial --typescript

위와 같은 명령어로 create-react-app에서 TypeScript를 같이 도입해 구축한다.

props 설정해주기

import React from 'react';

type GreetingsProps = {
  name: string;
  mark: string;
  optional?: string;
};

function Greetings({ name, mark, optional }: GreetingsProps) {
  return (
    <div>
      Hello, {name} {mark}
      {optional && <p>{optional}</p>}
    </div>
  );
}

Greetings.defaultProps = {
  mark: '!'
};

export default Greetings;

props로 받는 객체의 type을 설정해줄 수 있다. 그 type은 type alias 형태로 만들어 줄 수 있다.
'?' 는 있어도 되고 없어도 되는 optional의 특징을 갖고 있어서 이를 활용해
&&를 활용한 조건부 렌더링을 적절히 사용해줄 수 있을것 같다.
또한, defaultProps도 정해줄 수 있다.

useState와 함께 사용

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState<number>(0);
  const onIncrease = () => setCount(count + 1);
  const onDecrease = () => setCount(count - 1);
  return (
    <div>
      <h1>{count}</h1>
      <div>
        <button onClick={onIncrease}>+1</button>
        <button onClick={onDecrease}>-1</button>
      </div>
    </div>
  );
}

export default Counter;

useState 와 같은 형태로 Generics을 사용할 수 있다. 하지만 Generics를 사용하지 않아도 알아서 타입을 유추하기 때문에 생략 가능하다.
하지만 상태가 null일 수도 있고 아닐수도 있을 때, 혹은 상태의 타입이 까다로운 구조를 가진 객체이거나 배열일 때는 Generics을 사용하는게 좋다고 한다.

// null이거나 아닐때
type Information = { name: string; description: string };
const [info, setInformation] = useState<Information | null>(null);
// 배열일 때
type Todo = { id: number; text: string; done: boolean };
const [todos, setTodos] = useState<Todo[]>([]);

때문에 난 그냥 무조건 써보기로 했다.

useState, Props와 간단한 form 구현

src/MyFormPractice.tsx

import React, { useState } from "react";

type MyFormPracticeProps = {
  onSubmit: (form: { name: string; description: string }) => void;
}

function MyFormPractice({ onSubmit }: MyFormPracticeProps) {
  const [form, setForm] = useState({ name: '', description: '' });
  const { name, description } = form;

  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = event.target
    setForm({
      ...form,
      [name]: value
    });
  };

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    onSubmit(form);
    setForm({
      name: '',
      description: ''
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" value={name} onChange={onChange} />
      <input name="description" value={description} onChange={onChange} />
      <button type="submit">확인</button>
    </form>
  )
};

export default MyFormPractice;

src/App.tsx

import React from "react";
import MyFormPractice from "./MyFormPractice";

const App: React.FC = () => {
  const onSubmit = (form: { name: string; description: string }) => {
    console.log(form);
  }
  return <MyFormPractice onSubmit={onSubmit} />
}

export default App;

배운 내용을 다시 안보고 처음부터 혼자 코드를 작성해가며 간단하 input form 컴포넌트를 만들어봤다.
onChange나 onSubmit의 event가 어떤 type인지 알고 싶을때 마우스를 올려놓으면 뜨는 좋은 팁을 알 수 있었다.
함수의 매개변수로 전달해줄 인자에 객체 형식으로, 또 그의 프로퍼티들을 다시 type 지정해줄 수 있다. type alias를 활용해서!
역시 글만 읽어선 안되고 혼자 다시 코드를 구현해봤을 때 머리에 더 잘 들어오는것 같다.
TypeScript는 javascript 코드이지만 새로 알아야 할 규약, 규칙, 문법 등이 많은것 같으니 수시로 메모 해두고 기억해야 할 필요가 있다.

profile
Frontend Developer

0개의 댓글