Front-end/Typescript

    [Typescript] React에서 type, interface는 어디에 정의하는게 좋을까?

    [Typescript] React에서 type, interface는 어디에 정의하는게 좋을까?

    이 글의 디자인 패턴 부분은 TypeScript | Organizing and Storing Types and Interfaces (by Andres Reales)를 참고하여 작성하였습니다. 기본적으로는 컴포넌트 내부에 정의하되, 컴포넌트 간 의존성을 경계하기 만약 type이나 interface가 특정 컴포넌트에서만 필요한 것이라면 그냥 그 컴포넌트 내부에 정의하면 된다. 보통 이런 local적인 데이터에는 props가 있다. // StudentList 컴포넌트 interface Student { id: number; name: string; age: number; } interface StudentListProps { classNum: number; students: Student[]; } functi..

    [Typescript] 이미 존재하는 CRA에 Typescript 추가하기

    CRA 생성할 때부터 Typescript 설정하기 npx create-react-app my-app --template typescript 이랬다면 좋겠으나... 때로는 CRA 설치하고 온갖 라이브러리 설정도 다 해놓은 다음에 Typescript 설정을 하지 않았다는 사실을 알고 멘붕이 오기도 한다. 그 때는 TS에 필요한 패키지와 설정을 추가로 해주면 된다. 이미 존재하는 CRA에 Typescript 추가하기 1. 패키지 설치 npm install --save typescript @types/node @types/react @types/react-dom @types/jest 2. 파일 확장자 .ts 혹은 .tsx로 바꾸기 jsx 문법을 사용하고 있던 파일은 .tsx로, 순수 js 파일은 .ts로 확장자..

    [Typescript] interface vs type

    Interface와 Type Alias 일반적으로 object 타입에 대해 타입 선언을 할 때에는 둘에 별 차이가 없다. 선언 예시 interface Cat { name: string; age: number; } type Cat = { name: string; age: number; } // 사용은 둘 다 똑같다 const kitty: Cat = { name: 'Kitty', age: 5 } 다만 공식 문서의 type alias와 interface 항목을 보면 다음과 같이 정의되어 있다. type alias A type alias is exactly that - a name for any type. 변수 옆에 콜론(:)으로 직접 타입을 지정하던 것을 여러번 재사용하고 별칭을 지어주기 위한 목적으로 만들어..