Typescript 5

[TypeScript] Component Polymorphic하게 사용하기

잘못된 Polymorphic Component 예시 component 타입에 따라 필요한 props가 다름. 모든 props가 선택적(optional)으로 처리되어, 런타임에 필요한 props가 누락될 수 있음 ex) import React, { MouseEventHandler } from "react"; type ButtonType = "button" | "a"; interface ButtonProps { component: ButtonType; href?: string; onclick?: MouseEventHandler; children: React.ReactNode; } const Button = ({ component, href, onclick, children }: ButtonProps) => ..

Typescript 2024.01.27

[Tspec] TypeScrip 기반 OpenApi Spec,Swagger 만들기

Tspec TypeScript 타입과 JSDoc 기반으로 OpenApi를 자동으로 생성하게 해주는 라이브러리 https://ts-spec.github.io/tspec/ Tspec | Tspec Tspec Type-driven API Documentation Auto-generating REST API document based on TypeScript types ts-spec.github.io Tspec 사용 방법 1. 의존성 주입 npm install tspec yarn install tspec 2. 타입 지정하기 주의사항 never 등 특정 타입들 인식 못하는 버그 있음 알리아스로 import 하면 타입 인식 못하고 string으로 나오는 버그 있음 ex) type.ts /** 회원 종류 KEY */..

Typescript 2023.07.09

[TypeScript] 타입들 optional하게 변형하기

타입을 넘겨받고 해당 Optional하게 바꾸기 /** `T`의 모든 속성을 순회하며 optional로 수정 */ export type DeepPartial = { [P in keyof T]?: DeepPartial; }; /** 특정 key를 제외하고 optional로 변환 */ export type PartialExcept = Partial & Pick; /** 특정 key를 제외하고 모든 속성을 optional로 변환 */ export type DeepPartialExcept = DeepPartial & Pick; /** 특정 key만 optional로 변환 */ export type PartialKeys = Partial & Omit extends infer O ? { [P in keyof O]:..

Typescript 2023.04.27

[Effective TypeScript] item52 테스팅 타입의 함정에 주의하기

item52 테스팅 타입의 함정에 주의하기 유의점 1 : 반환값에 대한 테스트를 진행하지 않는다. 실행에서 오류가 발생하지 않는지만 체크한다. const square = (x: number) => x * x; // 실행에서 오류가 발생하지 않는지만 체크한다. test("square a number", () => { square(1); square(2); }); 해결책 반환 타입을 지정해 준다. declare function map(array: U[], fn: (u: U) => V): V[]; const lengths: number[] = map(["john", "paul"], (name) => name.length); // 불필요한 변수를 선언해야한다. // 불필요한 변수를 선언안해도 되는 개선된 코드 ..

Typescript 2023.04.04

[Effective TypeScript] item51 의존성 분리를 위해 미러 타입 사용하기

item51 의존성 분리를 위해 미러 타입 사용하기 미러링 작성중인 라이브러리가 의존하는 라이브러리의 구현과 무관하게 타입에만 의존한다면, 필요한 선언부만 추출하여 작성 중인 라이브러리에 넣는것 미러링을 사용하지 않은 CSV 파일 파싱 라이브러리 // Buffer Type은 NodeJs 타입 선언 설치해서 얻을수있음 // npm install --save-dev @types/node function parseCSV(contents: string | Buffer): {[column: string]: string}[] { if (typeof contents === 'object') { // 버퍼인 경우 return parseCSV(contents.toString('utf8')); } ... } 해당 파일 파..

Typescript 2023.04.04