React with TypeScript

Seo·2020년 5월 8일
0

Front-End

목록 보기
9/21

TypeScript ?!?

Superset of javascript
(자바스크립트 + @)

코드 스타일은 겪어본 언어 중에서 Python 3.6에서 명시적 타입을 지정해주는 스타일과 비슷해보인다.

Typing

타입을 명시적으로 지정해줘서 컴파일 단계에서 알아차릴 수 있도록 한다.
(C#을 다뤘던 개발자여서 그런가 오히려 js(또는 python) 암묵적 타입선언에 대해서 장점으로 생각했는데, 명시적 타입입력이 매우 귀찮기 때문에 매우 짧은 생각이었단 걸 프로그래밍을 해보면서 느꼈다.)

Ex1

  • javascript

    const plus = (a, b) => a + b;
    
    console.log(plus("one", 2)); //runtime error
  • typescript

    const plus = (a:number, b:number) => a + b;
    
    console.log(plus("one", 2)); //compile error

Ex2

  • javascript
    let hello = "hello";
    hello = 111111; //nothing
  • typescript
    let hello:string = "hello";
    hello = 111111; //compile error

Interface

object와 비슷한 형태

const seo = {
  name: "Seo",
  age: 333,
  isHuman: true
}

const helloToHuman = (human) => {
  console.log(`Hello ${human.name}`);
}

helloToHuman(seo);
helloToHuman(1);

//결과
//Hello seo
//Hello undefined <-undefined error  

위와 같이 javascript에서는 runtime 시에 1이라는 객체가 들어왔을 때 비로소 문제가 생겼다는 것을 알 수 있다.(왜냐하면 최대한 실행되도록 하기 때문에 일단 실행은 된다.)

typescript에서는 object 암묵적 타입이 문제가 될 수 있고 문제점을 알려줌
그러면 typescript에서는 어떻게 해결을 하는가? interface를 통해 object type들을 명시해준다.

const seo = {
  name: "Seo",
  age: 333,
  isHuman: true
}

interface IHuman = {
  name: string;
  age: number;
  isHuman: boolean;
  isGood?: boolean; // ? 글자를 붙이게 되면 optinal value가 된다. (boolen || undefined)
}

const helloToHuman = (human: IHuman) => {
  console.log(`Hello ${human.name}`);
}

helloToHuman(seo);

//결과
//Hello seo

React with Typescript

Quickstart

npx create-react-app project-name --typescript

--typescript : 옵션으로 주면 typescript 기반 react 프로젝트가 만들어진다.

tsconfig.json

프로젝트에서 사용할 ts에 대한 얼마나 strict할지에 대한 rules을 정리하는 파일

"compilerOptions": {
  "target": "es5",
  "lib": [
    "dom",
    "dom.iterable",
    "esnext"
  ],
  "allowJs": true,
  "skipLibCheck": true,
  ...
  
}

definitely typed

huge directory about types

https://github.com/DefinitelyTyped/DefinitelyTyped

typescript로 만들어진 ReactJS는 없지만 @types 을 제공해줌

모든 React의 functionality를 typescript로 설명해주고 typescript가 이해할 수 있도록 해준다.

yarn add styled-components
import styled form "styled-components";
//styled가 'any' type으로 typescript에서 에러가 뜬다.
yarn add @types/styled-components
import styled form "styled-components";
//@types/styled-components 설치 후에는 타입이 표시가 되면서 동작가능하게 된다.

만약에 원하는 lib에 대한 @types가 존재하지 않는다면 tsconfig.json에 가서

...
  "noImlicitAny": true
...
  
}

위와 같이 수정해줘야 any타입을 에러로 체크하지 않고 진행할 수 있다.

profile
개발관심자

0개의 댓글