- TypeScript 타입변수 추론 진단
Prettify— 교차 타입을 펼쳐 보기- 판별 유니온으로 props 조합 제한
Exclude로 빈 문자열 막기- 오버로드별 반환 타입 꺼내기
- 템플릿 리터럴 타입으로 이름 파생
기초 및 개념 이해
React와 TypeScript
- How to write a React Component in TypeScript
- How to Simplify Component Imports with TypeScript Namespaces
타입 시스템 심화 및 패턴
- Implementing a type-safe object builder in TypeScript
- Branded Types | Learning TypeScript
- https://effect.website/docs/guides/style/branded-types
- TypeScript enums: use cases and alternatives
- Pattern Matching in TypeScript with Record and Wildcard Patterns
- Did you know you can write your own typesafe React router in 500 lines? · OlegWock
성능 및 효율적인 코드 작성
- Performance · microsoft/TypeScript Wiki · GitHub
- Efficient Typescript
- One Thing Nobody Explained To You About TypeScript
스타일 가이드 및 실전 활용
- TypeScript Style Guide
- DefinitelyTyped/README.ko.md at master · DefinitelyTyped/DefinitelyTyped
- Effective TypeScript
- Blogged Answers: Learning and Using TypeScript as an App Dev and a Library Maintainer
Node.js 및 빌드 관련
함수형 프로그래밍과 TypeScript
마이그레이션 사례
- DevTools architecture refresh: migrating DevTools to TypeScript - Chrome Developers1
- Migrating Puppeteer to TypeScript - Chrome Developers
- ts-migrate: A Tool for Migrating to TypeScript at Scale | by Sergii Rudenko | The Airbnb Tech Blog | Medium2
- Migrating millions of lines of code to TypeScript3
- Etsy’s Journey to TypeScript - Code as Craft4
Footnotes
-
Chrome DevTools 및 Puppeteer를 TypeScript로 마이그레이션한 경험에 대한 설명 ↩
-
대규모 JavaScript 코드베이스를 TypeScript로 자동 마이그레이션하는 도구인 “ts-migrate”를 소개하는 Airbnb 엔지니어링 팀의 블로그 게시물 ↩
-
Flow에서 TypeScript로 마이그레이션한 경험을 설명하고 오픈소스 flow-to-typescript-codemod 도구에 대한 링크를 포함하는 Stripe 엔지니어링 팀의 블로그 게시물 ↩
-
Etsy 엔지니어링 팀이 대규모 웹 애플리케이션에서 TypeScript를 채택한 방법, 직면한 문제 및 얻은 이점을 설명 ↩
-- interface 의 호출 시그니처 = 함수 타입
type MathFn = Double -> Double -> Double -- interface MathFn { (a: number, b: number): number }
sum :: MathFn
sum a b = a + b -- const sum: MathFn = (a, b) => a + b — a·b 는 문맥에서 추론
-- 이 .js 가 JSX 를 쓰나 (CRA → Vite 로 옮길 때 .jsx 로 바꿀 파일 고르기)
isReactComponent :: String -> Bool
isReactComponent = any isJSXIdentifier . universe -- AST 어딘가에 JSXIdentifier 가 있나
. parseJSX Module Latest -- acorn.Parser.extend(acorn-jsx)
-- T extends R 은 "R 처럼 불러도 T 가 받아내나" — 오버로드면 시그니처 하나만 받아내면 된다
extends :: Overloaded -> Sig -> Bool
t `extends` r = any (`accepts` r) (signatures t)
accepts :: Sig -> Sig -> Bool
sig `accepts` r = arity sig <= arity r -- 1 더 요구하지 않는다 (남는 인자는 버린다)
&& params r `assignableTo` params sig -- 2 받는 인자 타입이 맞는다
&& ret sig `assignableTo` ret r -- 3 돌려주는 값이 R 자리에 들어간다
year = [ Sig [] Number, Sig [String] String ]
year `extends` Sig [] Number == True
year `extends` Sig [String] String == True
year `extends` Sig [Number] Number == True -- year() 가 u 를 버리고 받아낸다
-- infer 는 묻지 않고 꺼낸다: 마지막 시그니처에서. 인자 목록으로 오버로드를 고를 수 없다
returnType year == String -- 순서를 바꾸면 Number
(year `extends` Sig [] (Infer r)) == Never -- r = String 을 꺼낸 뒤 () => String 을 받아내는 시그니처가 없다
-- 직접 정의하면 오버로드 대신 제네릭 하나로
-- year<U extends [] | [string]>(...a: U): U extends [] ? number : string
-- 그러면 ReturnType<typeof y.year<[]>> 로 꺼낸다
-- 템플릿 리터럴 타입으로 prop 이름을 만든다 (TS 4.1+ key remapping)
type Names = "Title" | "Content" | "Actions"
type RenderProps = { [k in Names as "render" ++ k]: () -> Node }
-- == { renderTitle :: () -> Node, renderContent :: () -> Node, renderActions :: () -> Node }
dialog { renderTitle, renderContent, renderActions } =
div "root" [ div "content" [renderTitle (), renderContent ()]
, div "actions" [renderActions ()] ]
-- JSON 값 = 기본값 | 객체 | 배열, 객체·배열이 다시 JSON 값을 담는다
data JsonPrimitive = JString String | JNumber Double | JBool Bool | JNull
data JsonValue = Prim JsonPrimitive
| Obj (Map String JsonValue) -- type-fest: 선택 속성은 undefined 도 허용
| Arr [JsonValue] -- readonly 배열도
-- 직렬화 결과 타입까지 필요하면 type-fest 의 Jsonify-- 생성자는 항상 새 인스턴스를 준다. private 생성자 + static create 면 셋이 된다
create :: String -> Maybe User -- 1 실패를 값으로 (null / Result)
create name | length name < 3 = Nothing
| otherwise = Just (User name)
shape :: Kind -> Size -> Shape -- 2 하위 클래스를 고른다 (팩토리)
shape Circle = circle
shape Rect = rectangle
config :: IO Config -- 3 같은 인스턴스 (싱글톤): instance ??= new Config()
config = readIORef instanceRef >>= maybe (newConfig >>= cache) pure
-- 단순 초기화만이면 생성자가 더 직관적
-- Figma 권한 DSL: 정책을 JSON 으로 직렬화되는 식으로, 평가는 TypeScript 엔진 하나로
-- (이전: 불필요한 복잡성 · 계층 권한 비효율 · DB 부하 · 여러 진실 소스)
data Expr = Binary Field Op Value -- ['file.id', '<>', null]
| And [Expr] -- { and: [...] }
| Or [Expr] -- { or: [...] }
eval :: Row -> Expr -> Bool
eval r (Binary f op v) = apply op (r ! f) v
eval r (And es) = all (eval r) es
eval r (Or es) = any (eval r) es
canView = And [ Binary "file.id" "<>" Null, Binary "team.permission" "=" "open" ]-- verbatimModuleSyntax: 쓰임새를 추측하지 않고 표시대로만 지운다
emit :: Import -> Maybe Import
emit (Import Type _) = Nothing -- import type { A } — 통째로 지운다
emit i = Just i -- type 없는 import 는 그대로 남는다
-- 그래서 타입만 가져올 땐 표시해야 한다 (안 하면 TS1484)
import type { A } from 'a'
-- 기존 코드 일괄 수정: fix-verbatim-module-syntax
-- 제네릭 컴포넌트: <TRow extends Record<string, any>> 로 넘긴 rows 에서 row 타입을 줍는다
table :: (row <: Record String Any) => { rows :: [row], renderRow :: row -> Int -> Node } -> Node
table { rows, renderRow } = tbody (zipWith renderRow rows [0..])
-- 1 줍기: 선언(Props<TRow>)과 넘긴 값을 칸마다 나란히 놓고, 맨몸 TRow 자리에서 후보를 줍는다
infer { rows = [{ name = "lee" }] } -- [TRow] ↔ [{ name :: String }] → 후보 { name :: String }
-- renderRow 의 row 는 타입을 안 적어 주울 게 없다. extends 는 넘긴 값이 아니라 후보가 아니다
-- 정해진 TRow 가 거꾸로 renderRow 로 흘러가 row.name 이 된다
-- 2 고르기: 후보가 여럿이면 자리로 — 내주는 쪽(공변)이 받는 쪽(반변)에 들어가면 공변이 이긴다
pick { rows = dogs, renderRow = \(row :: Animal) (i :: Int) -> … } == Dog -- 다 적음: 함수 타입끼리 비교해 Animal 이 반변 후보, Dog 가 Animal 에 들어가니 공변이 이긴다
pick { rows = dogs, renderRow = \(row :: Animal) -> … } == Animal -- 덜 적음: 적힌 타입만 읽어 Animal 을 공변 후보로 넣고, Dog 와의 공통 상위를 고른다
-- 화살표 함수 리터럴일 때 얘기다. 이미 만든 함수면 덜 적어도 Dog, function 표현식은 다 적어도 Animal
-- 3 두 번째로 쓰는 자리는 NoInfer 로 줍기에서 뺀다 (TS 5.4+)
type Props row = { rows :: [row], renderRow :: row -> Int -> Node, selectedRow :: Maybe (NoInfer row) }
-- 없으면 selectedRow { name, age } 도 후보가 돼 union 으로 넓어지고 에러가 안 난다
-- 있으면 selectedRow 는 줍지 않아 TRow = { name } 이 되고, selectedRow 를 그 타입으로 검사하다 age 에서 에러가 난다
-- 4 extends Record<string, any> 는 원시값만 막는다 (= object)
-- Record<string, unknown> 은 type 별칭 객체만 — interface·배열·함수도 막힌다
-- 같은 패턴: downshift Combobox<T> 의 items → renderItem item
-- 교차 타입을 한 객체로 펼쳐 보여준다 (에디터 툴팁·에러 메시지용)
type Prettify t = { [k in keyof t]: t ! k } & {}
-- 매핑 타입이 속성을 다시 모은다
-- & {} 가 있어야 별칭 이름(Prettify<…>) 대신 펼친 모양이 뜬다 — & unknown 도 같다
-- 왜 그런지는 공식 설명이 없다: "a quirk of the TypeScript compiler" — Total TypeScript, The Prettify Helper (tsc 5.9.3 에서 확인)
show (Prettify ({ a :: 1 } & { b :: 2 })) == "{ a: 1; b: 2 }"
p :: Prettify (ComponentProps "div")
-- 리터럴 공통 속성(variant)으로 유니온을 가른다
data ModalProps = NoTitle -- variant: 'no-title'
| Title { title :: String } -- variant: 'title'
modal :: ModalProps -> Element
modal NoTitle = div "No title"
modal (Title t) = div ("Title: " ++ t) -- 이 분기 안에서 props 는 Title 로 좁혀진다
-- 초과 속성 검사도 variant 로 먼저 고른 멤버 하나에 대고 한다
check { variant = "no-title", title = "Oh dear" } -- ✗ NoTitle 에 title 없음
check {} -- ✗ variant 없음
-- 판별 속성이 없는 { a :: Int } | { b :: String } 은 { a = 1, b = "x" } 를 받는다 ("partial overlap")
-- 빈 문자열 src 를 타입으로 막는다
type NonEmptyString t = Exclude t ""
image :: (t <: String) => { src :: NonEmptyString t } -> Element
-- t <: String 제약이 있어야 넘긴 리터럴을 그대로 줍는다 (빼면 t = String 으로 넓어져 "" 도 통과)
infer (image { src = "" }) -- t = "" → Exclude "" "" = never ✗
infer (image { src = "ab" }) -- t = "ab" ✓
infer (image { src = s }) -- s :: String → t = String → String ✓ 값이 "" 여도
-- 인자 타입이 리터럴 "" 일 때만 막는 가드다 (const e: '' = '' 도 막힌다)
-- 왜 리터럴로 남나: 들어갈 자리가 primitive 제약을 가진 타입 변수면 리터럴 문맥으로 본다
-- 중첩 객체 타입의 안쪽만 바꾼다: 바깥에서 K 를 빼고, 같은 키로 다시 붙이며 안쪽을 고친다
type NestedOptional t k ok = Omit t k & { k :: Omit (t ! k) ok & Partial (Pick (t ! k) ok) }
type OverrideNested t k o = Omit t k & { k :: Omit (t ! k) (keyof o) & o }
type O = { actions :: { a :: String, b :: Number } }
NestedOptional O "actions" "b" == { actions :: { a :: String, b :: Maybe Number } }
OverrideNested O "actions" { b :: Bool } == { actions :: { a :: String, b :: Bool } }
-- 한두 곳이면 손으로 쓰는 게 더 명확하다. 반복될 때만 유틸리티
-- 값도 같은 방식으로: 라이브러리 객체를 변이하지 말고 펼쳐서 새로
modified = info { actions = (actions info) { onDownload = Nothing } }
-- 제네릭 기본값: <T extends Type = Default>. 생략하면 기본값, 기본값은 제약을 만족해야 한다
type Mode = 'single' | 'multiple'
type SelectProps (t :: Mode = 'Multiple') = { mode :: t, value :: Value t }
type family Value t where
Value 'Single = String
Value 'Multiple = [String]
a :: SelectProps -- t = 'Multiple
a = { mode = Multiple, value = ["a", "b"] }
b :: SelectProps 'Single
b = { mode = Single, value = "a" }
-- 매개변수마다 기본값
type ApiResponse (d = Any) (s :: Status = 'Loading) = { data' :: If (s == 'Success) d Null, status :: s }
-- 가장 자주 쓰는 경우를 기본값으로 — 매번 적지 않는다
-- 판별 유니온은 코드엔 좋은데 문서로 옮기기 어렵다
data Button = Submit { color :: String } -- type: 'submit'
| Reset { text :: String } -- type: 'reset'
-- 코드: 갈래마다 묶여 있다 — type 을 보면 나머지가 정해진다 (타입 검사·자동완성)
-- 문서 표: 속성마다 한 줄이라 갈래가 조건 문장으로 풀린다
docs = [ ("type", "'submit' | 'reset'", "필수")
, ("color", "string", "type = 'submit' 일 때 필수")
, ("text", "string", "type = 'reset' 일 때 필수") ] -- 갈래가 늘면 표가 복잡해진다
-- 그래서 정의 파일을 원본으로 두고 생성한다: typedoc · api-extractor
-- 간단한 Redux 스타일 store: 상태 하나 + 리스너 목록 하나
createStore :: (s -> a -> s) -> s -> Store s a
createStore reducer s0 = Store { getState, subscribe, dispatch } -- s0: 만들 때 리듀서와 함께 넘기는 초기 상태 (preloadedState)
where
getState = read state
dispatch a = do s' <- reducer <$> read state <*> pure a
state := s'
mapM_ ($ s') =<< read listeners
pure a
subscribe l = do l =<< read state -- 지금 상태로 한 번 곧바로
listeners %= (l :)
pure (listeners %= filter (/= l)) -- 해지 함수
-- null 일 수 있는 단계를 체크 없이 잇는다
fmap :: (a -> b) -> Maybe a -> Maybe b
fmap f (Just x) = ofNullable (f x) -- 결과가 null 이면 Nothing 으로
fmap _ Nothing = Nothing -- 뒤 단계는 부르지 않는다
scrollTo id = ofNullable scrollElement
>>= querySelector ("#" ++ id)
>>= (listToMaybe . getClientRects)
<&> \rect -> root.scrollLeft := left rect
-- generator 로 쓰면 같은 모양의 early return
handleScroll id = do
root <- scrollElement -- if (!root) return
target <- querySelector ("#" ++ id) root -- if (!target) return
yield (maybe 0 left (listToMaybe (getClientRects target)))
-- TypeScript 로 Maybe 를 만든다: Just·Nothing 두 클래스에 bind 하나씩
data Maybe a = Just a | Nothing
bind :: Maybe a -> (a -> Maybe b) -> Maybe b
bind (Just x) f = f x -- class Just { bind(fn) { return fn(this.value) } }
bind Nothing _ = Nothing -- class Nothing { bind(fn) { return this } } — fn 을 안 부른다
safeDivide :: Double -> Double -> Maybe Double
safeDivide _ 0 = Nothing
safeDivide x y = Just (x / y)
Just 10 `bind` (`safeDivide` 2) == Just 5
Just 10 `bind` (`safeDivide` 0) == Nothing
-- isLoading 없이 onClick 에서 yield 만 한다 — 시간이 코드의 한 방향(↓)으로만 흐를 때
-- 멀티 단계 loading · progressive search · optimistic mutation(optimistic | reconciled | rolledBack)
data Status = Idle | Running | Errored | Done
data Event a = Start | Yield a | Finish | Throw Error | Cancel
step :: State a -> Event a -> State a
step s Start = s { status = Running, error = Nothing } -- 상태와 에러 초기화가 한 번에 — 따로 set 하다 어긋날 일이 없다
step s (Yield v) = s { value = v } -- status 는 두고 값만
step s Finish = s { status = Done }
step s (Throw e) = s { status = Errored, error = Just e }
step s Cancel = s { status = Idle } -- 없으면 Running 에 멈춘다
-- 핸들러는 값의 흐름(async generator), 훅은 그걸 접는다
state = foldl step initial (run fn args)
run :: (Signal -> args -> Stream a) -> args -> [Event a]
run fn args = Start : map Yield (untilAborted (fn signal args)) ++ end
where end | aborted = [] -- abort 로 생긴 throw 는 에러가 아니다
| otherwise = [Finish] -- 본문 어디서 throw 하든 Throw e
-- run 은 직전 실행을 abort 하고 다시 시작한다 · unmount 도 abort
-- 재진입 정책은 쓰는 쪽이 고른다
-- 버튼: Running 동안 disabled, yield 한 JSX 가 곧 라벨
-- 검색: run 마다 재시작 — tier 경계(await wait)가 곧 취소 지점이라 debounce 가 필요 없다
searchTiers q = do wait 100; yield [q ++ ":local"]
wait 300; yield [q ++ ":local", q ++ ":remote"]
-- 확인: a 를 치고 150ms 에 ab
shown == [["a:local"], ["ab:local"], ["ab:local", "ab:remote"]] -- a:remote 는 끼어들지 않는다
-- 같은 배열을 이름으로 반복 조회해 O(n) 스캔이 계속 도는데, 배열이 언제 바뀌는지 추적하기 싫을 때
-- 캐시 키를 배열의 내용이 아니라 참조로 둔다 — 무효화를 참조 동등성에 맡긴다
lookup :: Ref [Item] -> Name -> Cache -> (Maybe Id, Cache)
lookup items name cache = case WeakMap.get items cache of
Just index -> (Map.lookup name index, cache) -- 여기부터 O(1)
Nothing -> let index = buildIndex (deref items) -- 새 참조면 자동 miss, 한 번 O(n)
in (Map.lookup name index, WeakMap.set items index cache)
-- delete·clear 가 어디에도 없다: 불변 업데이트면 "데이터가 바뀜" = "참조가 바뀜"
-- 키가 weak 이라 옛 items 가 안 잡히면 entry 도 GC 된다. Map 이면 영구히 붙들려 누수
-- 결과는 참조만 보고 정해진다 — 내용은 보지 않는다
outcome :: SameRef -> SameContent -> Outcome
outcome True True = Hit
outcome False False = Rebuild -- refetch. 옛 인덱스는 옛 배열과 함께 GC
outcome False True = Miss -- 매번 [...data]·data.filter() 로 넘긴다 — 무의미
outcome True False = Wrong -- push·splice 로 제자리에서 바꿨다 — 느린 게 아니라 틀린 값
-- TanStack Query 의 data·select 결과는 참조가 안정적이라 그대로 넘기면 된다
-- 된 것: 같은 참조로 두 번 불러 buildIndex 가 한 번만 돈다
-- 화면마다 dayjs().format('…') 이 흩어져 같은 날짜가 다르게 찍힌다: 허용 표기를 타입으로 닫는다
-- 매핑 객체({ DATE: 'YYYY-MM-DD', … })는 i18n 습관이다 — i18n 은 이름표(인사)와 내용(Hello)이 달라서 짝짓기가 필수였다
-- dayjs 는 포맷 문자열이 곧 키이자 값 — 이름을 붙인 매핑 객체는 같은 정보를 두 번 든다
formats :: [Format] -- 단일 출처 (DATE_FORMATS as const)
formats = [ "YYYY-MM-DD", "YYYY-MM-DDTHH:mm:ss", "HH:mm", "YYYY년 M월", "YY년 M월 D일"
, "YYYY.MM.DD", "YY.MM.DD", "YYYY.MM.DD(ddd)", "YYYY.MM.DD HH:mm" ]
type DateFormat = { f :: Format | f ∈ formats } -- 배열에서 파생된 닫힌 union, 따로 손댈 곳 없음
formatDate :: Date -> DateFormat -> String -- 유일한 진입점
formatDate d f = format (dayjs d) f
-- 새 표기는 여러 화면에서 통일이 필요할 때만 formats 에 넣는다. 일회성('M.D')은 raw 로
-- 이 기준이 없으면 배열이 잡동사니 enum 이 된다
-- 구멍: raw 우회는 타입이 못 막는다 (no-restricted-syntax 규칙 전까지 단일 출처는 관행)
-- 구멍: "ddd" 는 locale "ko" 없이 Mon·Tue 로 조용히 샌다 — 런타임 전제를 가진 유일한 항목
-- TS 7 content mapper 가 transform 요청을 받으면: CSS 모듈 → TS 모듈 + 대응표 + 진단
transform :: Options -> Content -> Result
transform opts = stripBom >>> parse >>> collectLocals >>> exportsOf (localsConvention opts)
>>> render opts >>> shiftBom
-- BOM: postcss 가 떼므로 그만큼 원본 위치·진단 위치를 다시 민다
-- ① 오타 하나가 이 파일을 import 하는 모든 곳을 깨지 않게
parse :: CSS -> (Root, [Diagnostic])
parse css = case postcss css of
Right root -> (root, [])
Left err -> (safeParse css, [syntaxError err]) -- 진단을 남기고 살릴 수 있는 만큼 살린다
-- ② 내보낼 이름과, CSS 에 적힌 그 이름의 위치 (escape 포함) — 이 위치가 ④의 대응 끝점이다
locals :: Node -> [Local]
locals (Rule ":export" decls) = map prop decls -- ICSS: 키 그대로
locals (Rule sel) | inKeyframes = [] -- from·to·50% 는 이름이 아니다
| otherwise = classesAndIds sel -- :global(…) 안은 빼고, 인자 없는 :global 은 뒤쪽 전부를 뺀다
locals (AtRule "keyframes" name) = [name] -- :global 이면 없음
locals (AtRule "value" params) = valueNames params -- @value a: … / @value a, b as c from "…"
locals (AtRule "scope" params) = parenthesized params >>= classesAndIds -- @scope (.card) to (.content)
locals (Decl "composes" v) = [] -- 대신 검사: 이 파일에 없는 클래스면 진단, from 이 붙으면 건너뜀
-- 같은 이름은 처음 것만. hover 문서 = 앞의 /** */ 주석 + 선언 CSS (12줄까지)
-- ③ 이름 → 키. Vite 의 css.modules.localsConvention 과 같은 값
keys :: Convention -> Name -> [Key]
keys CamelCase n = [n, camelCase n] -- camelCase = lodash.camelcase (postcss-modules 와 같게)
keys CamelCaseOnly n = [camelCase n]
keys Dashes n = [n, dashesCamelCase n] -- 대시 뒤 글자만 대문자로
keys DashesOnly n = [dashesCamelCase n]
keys _ n = [n]
-- ④ TS 를 써 내려가다 키를 쓰는 순간, 그 자리를 원본 이름 자리에 잇는다
emitKey :: Key -> Local -> Writer (Text, [SpanMapping]) ()
emitKey key local = do
here <- length <$> text
tell ( key
, [(here, length key, start local, length local, Alias, Hover .|. Definition .|. References .|. DocumentHighlights)] )
-- Alias: 키(btnPrimary)와 원본(btn-primary)이 달라도 에러·정의로 가기는 원본 이름에 붙는다
render :: Options -> [(Key, Local)] -> (Text, [SpanMapping])
render opts exports =
[ "declare const styles: { readonly " <> emitKey k l <> ": string; … }; export default styles;" | defaultExport opts ]
-- 식별자가 아닌 키는 "btn-primary" 문자열 키로
-- styles 라는 키가 있으면 바인딩을 _styles 로
<> [ "export declare const " <> emitKey k l <> ": string;" | namedExports opts, isBindingName k ]
-- 식별자이고 예약어가 아닐 때만
`orElse` "export {};" -- 내보낼 게 없어도 모듈이어야 한다