스파르타코딩클럽 내일배움캠프 TIL66

한재창·2023년 2월 1일
0

TypeScript 복습

Introduction

  • TS는 JS를 기반으로 한 프로그래밍 언어
  • TS는 strongly-typed => 프로그래밍 언어가 작동하기 전에 type을 확인한다.
  • 브라우저가 이해할 수 있는 유일한 언어는 JS이고 그렇기 때문에 TS는 이해하지 못한다.
  • 코드에 문제가 없는 것이 확인되면 TS가 컴파일해서 평범한 JS코드를 리턴한다.
// TS: "name"이 존재하지 않는다고 코드가 실행되기 전에 에러가 뜬다.
// JS: 코드가 실행되고 undefined가 뜬다.

const user = {
  firstName: "angela",
  lastName: "Davis",
  role: "Professor",
};

console.log(user.name);


const plus = (a: number, b: number) => a + b;
plus(1, 1);
plus("1", 1); // number가 아니기 때문에 Error

DefinitelyTyped

  • 파일을 만들 때 TS 설치 방법

    • npm : npx create-react-app my-app --template typescript
    • yarn : yarn create-react-app my-app --template typescript
  • 기존 파일에 TS 설치 방법

    • npm install --save typescript @types/node @types/react @tpyes/react-dom @types/jest
    • 파일 확장자 이름을 js > ts / jsx > tsx 로 변경한다.
  • TS는 라이브러리나 패키지가 뭔지 모르기 때문에 d.ts를 install 해줘야한다.

    • 라이브러리 or 패키지 설치 : npm i styled-components
    • d.ts install : npm i --save-dev @types/styled-components
      • @types ? Github repository인데, 유명한 npm 라이브러리를 가지고 있는 저장소,
      • 여기에서 라이브러리나 패키지의 type definition을 알려준다.

사용해보기

import styled from "styled-components";
import React, { useState } from "react";

// Container가 받는 Props를 타입을 설명해주는 방법
// 여기서는 borderColor이 Optional이 아니라서 Container에 무조건 써줘야한다.
interface ContainerProps {
  bgColor: string;
  borderColor: string;
}

// Container가 받는 Props를 TS에게 설명해준다.
const Container = styled.div<ContainerProps>`
  width: 200px;
  height: 200px;
  background-color: ${(props) => props.bgColor};
  border-radius: 100px;
  border: 1px solid ${(props) => props.borderColor};
`;

// Props에게 타입을 설명해주는 방법
// 여기에서는 borderColor이 Optional라서 App.tsx에서 borderColor props를 보내주지 않아도 에러가 뜨지 않는다.
interface CircleProps {
  bgColor: string;
  borderColor?: string;
}

// bgColor의 타입은 CircleProps의 object 라고 말해주고 있다.
// TS는 CircleProps 안에 bgColor 가 있다는 걸 알게 됨
export default function Circle({ bgColor, borderColor }: CircleProps) {
  // number로 시작하면 타입이 number이라고 타입 추론을 하고, number가 아닌 다른 값을 setCounter 해주면 에러가 뜬다.
  // 대부분 우리가 state를 만들 때, state의 타입은 변하지 않기 때문에 웬만하면 따로 type를 지정해주지 않아도 된다.
  const [counter, setCounter] = useState(1);

  // 만약 기존의 타입말고 다른 타입을 갖길 원할 때 하는 방법
  const [value, setValue] = useState<number | string>();

  // default 값을 보내는 법 : borderColor가 있다면 borderColor를 사용하고, 만약 undefined 라면 bgColor를 borderColor로 사용해라.
  return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor} />;
}

interface PlayerShape {
  name: string;
  age: number;
}

const sayHello = (playerObj: PlayerShape) =>
  `Hello ${playerObj.name} you are ${playerObj.age} years old.`;

sayHello({ name: "JC", age: 13 });
sayHello({ name: "JC", age: 13, health: 10 }); // interface에 health가 존재하지 않기 때문에 Error
profile
취준 개발자

0개의 댓글