React/노마드코더 React_Master

[ReactMaster] TypeScript

seung_hyeon 2024. 7. 24. 00:13

#3 TypeScript

 

• TypeScript

JavaScript를 기반으로 한 프로그래밍 언어

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

 

- TypeScript 설치

 

1.  새로 시작

npx create-react-app 내 앱 이름 --template typescript
npm i --save-dev @types/styled-components
npm i styled-components

 

2. 기존 프로젝트에 추가

1. npm install --save typescript @types/node @types/react @types/react-dom @types/jest
2. src 폴더 안에 있던 App.js와 index.js 파일을 App.tsx와 index.tsx 로 바꾼다.
3. "npx tsc --init" 명령어로 tsconfig.json 파일 생성 후, tsconfig.json 파일에 "jsx": "react-jsx"추가
-------------------------------------------
{
"compilerOptions": {
......
"jsx": "react-jsx"
}
}
-------------------------------------------
4. src/index.tsx에서 수정
--------------------------------------------------------------
import ReactDOM from "react-dom/client"

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
---------------------------------------------------------------
5. npm i --save-dev @types/styled-components

 

 

 

• interface

객체모양을 TypeScript에게 설명해 주는 것

+) interface: TypeScript와 코드가 실행되기 전에 확인

     prop type: 고드 실행 후 브라우저에 에러 뜬다

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

➣ type을 알려준다

 

 

<default props>

interface ContainerProps {
    bgColor: string;
}

const Container = styled.div<ContainerProps>`
    width: 200px;
    height: 200px;
    background-color: ${(props) => props.bgColor}; 
    border-radius: 100px;
`;

interface CircleProps {
    bgColor: string;
}

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

➣ interface 사용하여 ContainerProps, CircleProps의 object 설정

◦ <ContainerProps>: ContainerProps에 정의된 props 받음

◦ background-color: ${(props) => props.bgColor}: 배경색 bgColor prop의 값으로 설정

 

<optional props>

interface ContainerProps {
    bgColor: string;
    borderColor: string;
}

const Container = styled.div<ContainerProps>`
    width: 200px;
    height: 200px;
    background-color: ${(props) => props.bgColor}; 
    border-radius: 100px;
    border: 1px solid ${props => props.borderColor};
`;

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

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

 

➣ 선택적으로 사용할 때는 ? 사용

Container에서 borderColor required이기 때문에 Container에서 설정해야 한다

◦ borderColor={borderColor?? bgColor} → borderColor 있으면 사용, 없으면 borderColor를 bgColor로 사용

 

+ <Es6 JavaScript>

prop에  기본값 주는 방법

interface CircleProps {
    bgColor: string;
    borderColor?: string;
    text?: string;
}

function Circle({ bgColor, borderColor, text="default text"}: CircleProps) {
   return (
   <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}>
    {text}
    </Container>
   );
}

➣ text 존재 x : default text 출력

 

 

 

• State

+) string 또는 number 타입

많이 사용하지 않음!

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

 

 

<ReactJs + TypeScript>

event에 타입 지정 방법

function App() {
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);
  };
  return (
    <div>
      <form onSubmit={onSubmit}>
        <input 
        value={value} 
        onChange={onChange}
        type = "text" 
        placeholder='username' />
        <button>Log in</button>
      </form>
    </div>
  );

 

◦ input의 value를 state value 

◦ target = currentTarget 같은 것 (ReactJs Typescript에서 사용)

 

 

 

• Theme

<darkTheme / lightTheme>

<index.tsx>

import React from 'react';
import ReactDOM from 'react-dom/client';
import { ThemeProvider } from 'styled-components';
import App from './App';
import {darkTheme, lightTheme} from "./theme";

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

 

<App.tsx>

import styled from "styled-components";

function App() {
  const Container = styled.div`
    background-color: ${(props) => props.theme.bgColor};
    `;
  const H1 = styled.h1`
    color: ${(props) => props.theme.textColor}
  `;
  return (
    <Container>
      <H1>protected</H1>
    </Container>
  );
}

export default App;

 

const H1 (대문자) 소문자로 하면 h1 글씨색 바뀌지 않음

+) React components 규칙

- 대문자로 시작: styled-components로 인식

- 소문자로 시작: html 요소로 인식

 

<styled.d.ts>

import 'styled-components';

// amd extend them!
declare module 'styled-components' {
    export interface DefaultTheme{
            textColor: string;
            bgColor: string;
            btnColor: string;
    }
}

 

<theme.ts>

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",
};

 

lightTheme

 

darkTheme

 

 

 

• Recap

- JavaScript: 코드 작성 → 즉시 실행

- TypeScript: 코드 작성 → 그 값들이 어떤 타입들인지 알려주고 검사 후 실행 (실수 존재 시 코드 실행 멈춤)

- a: number → a는 무조건 number여야 한다 (자주 사용 x)

- 컴포넌트의 prop들에 타입 지정 (components 생성 후 prop 보낸다) (자주사용)

- interface: TypeScript에게 오브젝트 내의 데이터를 설명

'React > 노마드코더 React_Master' 카테고리의 다른 글

[ReactMaster] Styled components  (0) 2024.07.23