타입스크립트 치트시트
검색과 인쇄가 가능한 타입스크립트 참고자료입니다: 타입, 인터페이스, 제네릭, 유틸리티 타입, narrowing, 선언 파일, tsconfig까지. 무료입니다.
Basic types
14let name: string = "Ada";
let age: number = 30;
let ok: boolean = true;
let ids: number[] = [1, 2];
let pair: [string, number] = ["a", 1];
let anything: unknown;
let loose: any;
function log(): void {}
function fail(): never { throw new Error(); }
let big: bigint = 9007199254740993n;
let id: string | null = null;
const point = { x: 1 } as const;
enum Status { Active, Inactive }
type Dir = "up" | "down";
Interfaces & type aliases
12interface User { id: number; name: string; }
type User = { id: number; name: string };
interface User { nickname?: string; }
interface User { readonly id: number; }
interface Admin extends User { role: string; }
type Admin = User & { role: string };
interface Dict { [key: string]: number; }
interface Fn { (x: number): string; }
interface User { greet(): void; }
interface Box<T> { value: T; }
interface Window { myGlobal: string; }
type Point = Readonly<{ x: number }>;
Unions, intersections & narrowing
12type Id = string | number;
type Full = A & B;
if (typeof id === "string") { ... }
if (el instanceof HTMLElement) { ... }
if ("radius" in shape) { ... }
if (value != null) { ... }
switch (shape.kind) { case "circle": ... }
type Shape = Circle | Square;
const x = cond ? a : b;
user?.address?.city
const name = input ?? "default";
function assertNever(x: never): never { throw x; }
Generics
11function first<T>(arr: T[]): T { return arr[0]; }
first<string>(["a", "b"])
interface Box<T> { value: T; }
class Stack<T> { items: T[] = []; }
type Pair<K, V> = { key: K; value: V };
<T extends { id: number }>
<T, K extends keyof T>(obj: T, key: K): T[K]
<T = string>
function wrap<const T>(v: T): T[]
type Flatten<T> = T extends Array<infer U> ? U : T;
const map = new Map<string, User>();
Utility types
14Partial<User>
Required<User>
Readonly<User>
Pick<User, "id" | "name">
Omit<User, "password">
Record<string, number>
Exclude<T, U>
Extract<T, U>
NonNullable<T>
ReturnType<typeof fn>
Parameters<typeof fn>
Awaited<Promise<string>>
InstanceType<typeof MyClass>
Uppercase<"id"> / Capitalize<"id">
Functions & overloads
11function add(a: number, b: number): number
const add = (a: number, b: number) => a + b;
function log(msg: string, level?: string)
function log(msg: string, level = "info")
function sum(...nums: number[]): number
type Handler = (e: Event) => void;
function get(id: number): User;
function get(ids: number[]): User[];
function get(x: any): any { ... }
function fn(this: HTMLElement, e: Event)
async function load(): Promise<User>
function isUser(x: unknown): x is User
const fn: typeof otherFn = ...;
Classes
12class User { constructor(public name: string) {} }
private secret: string;
#secret: string;
protected id: number;
readonly createdAt = new Date();
static create(): User { return new User(); }
class Admin extends User { ... }
class Api implements Fetcher { ... }
abstract class Shape { abstract area(): number; }
get fullName(): string { return ...; }
override toString(): string { ... }
declare id: number;
Type guards & assertions
11function isUser(x: unknown): x is User
function assertUser(x: unknown): asserts x is User
function assertOk(x: unknown): asserts x
const el = input as HTMLInputElement;
value!
x as unknown as Y
const roles = ["admin", "user"] as const;
if (Array.isArray(value)) { ... }
satisfies Record<string, string>
typeof x === "object" && x !== null
catch (e) { if (e instanceof Error) ... }
Mapped & conditional types
12type Flags<T> = { [K in keyof T]: boolean };
{ [K in keyof T]?: T[K] }
{ [K in keyof T]-?: T[K] }
{ readonly [K in keyof T]: T[K] }
{ -readonly [K in keyof T]: T[K] }
{ [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] }
type IsString<T> = T extends string ? true : false;
T extends (infer U)[] ? U : never
type Keys = keyof User;
type Value = User["name"];
type Route = `/users/${number}`;
T extends any ? T[] : never
Modules & declaration files
12export interface User { ... }
export default class Api { ... }
import { User } from "./user";
import type { User } from "./user";
export type { User };
import * as path from "node:path";
declare module "my-lib" { ... }
declare global { interface Window { ... } }
declare const VERSION: string;
export {};
/// <reference types="node" />
npm i -D @types/lodash
tsconfig essentials
13"strict": true
"target": "ES2022"
"module": "ESNext"
"moduleResolution": "bundler"
"noEmit": true
"esModuleInterop": true
"skipLibCheck": true
"noUncheckedIndexedAccess": true
"paths": { "@/*": ["./src/*"] }
"outDir": "./dist", "rootDir": "./src"
"sourceMap": true, "declaration": true
npx tsc --noEmit
npx tsc --init
“:q”와 일치하는 항목이 없습니다.
타입스크립트 치트시트 소개
이 타입스크립트 치트시트는 타입 시스템을 검색 가능한 한 페이지로 정리했습니다: 기본 타입, 인터페이스와 타입 별칭, 유니온, 인터섹션과 narrowing, 제네릭, 내장 유틸리티 타입, 함수와 오버로드, 클래스, 타입 가드와 단언, 매핑 및 조건부 타입, 모듈과 선언 파일, 그리고 실제로 중요한 tsconfig 옵션까지 다룹니다.
일상적인 작업을 위해 작성되었습니다: 제네릭 제약의 정확한 형태, Pick, Omit, Record, ReturnType이 하는 일, 판별 유니온(discriminated union)이 어떻게 narrowing되는지, 캐스팅 대신 `satisfies`를 써야 할 때 등을 핸드북을 찾아보지 않고도 에디터에서 바로 확인할 수 있습니다.
이 그룹의 다른 치트시트와 마찬가지로 무료이며 클라이언트 측에서 동작합니다: 검색창으로 실시간으로 행을 필터링하고, 고정된 목차로 섹션을 이동하고, 클릭 한 번으로 스니펫을 복사하고, 책상에서 참고할 수 있도록 페이지를 인쇄할 수 있습니다.
타입스크립트 치트시트 사용 방법
- 시트를 열고 기본 타입과 제네릭부터 tsconfig 핵심까지 섹션을 훑어보세요.
- Partial, narrowing, satisfies 같은 키워드를 검색해 모든 행을 실시간으로 필터링하세요.
- 고급 타입 레벨 문법이 필요할 때는 유틸리티 타입이나 매핑 및 조건부 타입 섹션으로 이동하세요.
- 스니펫이나 복사 아이콘을 클릭해 타입스크립트 코드를 클립보드에 복사하세요.
- 전체 타입스크립트 참고자료를 종이로 보려면 인쇄를 사용하세요.