Menu
Coddy logo textTech

TypeScript チートシート

最終更新

基本型

プリミティブ型と変数への注釈の付け方。

操作構文
文字列let name: string = "Ada";
数値let age: number = 25;
真偽値let ok: boolean = true;
T の配列let xs: number[] = [1, 2, 3];
ジェネリック配列let xs: Array<string> = [];
タプルlet pair: [string, number] = ["a", 1];
Any (型付けを外す)let x: any = 1;
Unknown (安全な any)let x: unknown = JSON.parse(s);
Void (戻り値なし)function log(): void { … }
Never (戻らない)function fail(): never { throw … }
Null / undefinedlet n: null = null;

型推論と注釈

TS に推論させるか、自分で注釈するかの目安。

操作構文
値から推論let count = 0; // number
明示的な注釈let count: number = 0;
関数の引数function add(a: number, b: number) { … }
戻り値の型function add(a: number, b: number): number { … }
アロー関数const sq = (x: number): number => x * x;
型アサーションconst el = input as HTMLInputElement;
const アサーション (リテラル)const dirs = ["up", "down"] as const;
非 null アサーションel!.focus();

インターフェース

オブジェクトの形を記述する。

操作構文
宣言interface User { id: number; name: string; }
オプショナルなプロパティinterface User { age?: number; }
readonly プロパティinterface User { readonly id: number; }
メソッドシグネチャinterface Logger { log(msg: string): void; }
他のインターフェースを継承interface Admin extends User { role: string; }
インデックスシグネチャinterface Map { [key: string]: number; }
クラスで実装class Db implements Logger { … }

type alias とユニオン

型に名前を付け、| と & で組み合わせる。

操作構文
type aliastype ID = string | number;
オブジェクト aliastype User = { id: number; name: string };
ユニオン型type Status = "idle" | "loading" | "done";
インターセクション型type Admin = User & { role: string };
リテラル型type Yes = "yes";
Nullabletype Maybe<T> = T | null | undefined;
関数の aliastype Handler = (e: Event) => void;

関数

型付き引数、戻り値、オーバーロード。

操作構文
オプショナル引数function greet(name?: string) { … }
デフォルト引数function greet(name = "friend") { … }
可変長引数function sum(...ns: number[]): number { … }
関数型let fn: (a: number) => number;
呼び出し可能なインターフェースinterface Fn { (x: number): number; }
オーバーロードシグネチャfunction f(x: string): string; function f(x: number): number; function f(x: any) { return x; }
void 戻り値は無視されるconst cb: () => void = () => 42; // ok

クラス

アクセス修飾子と引数プロパティを持つクラス。

操作構文
クラスを宣言class User { name: string; }
コンストラクタconstructor(name: string) { this.name = name; }
引数プロパティconstructor(public name: string) {}
public / private / protectedprivate id: number;
readonly フィールドreadonly id: number;
静的メンバstatic count = 0;
getter / setterget name() { return this._name; }
継承class Admin extends User { … }
抽象クラスabstract class Shape { abstract area(): number; }

ジェネリクス

他の型でパラメータ化する再利用可能な型。

操作構文
ジェネリック関数function id<T>(x: T): T { return x; }
明示的な型で呼び出すid<string>("hi");
ジェネリックインターフェースinterface Box<T> { value: T; }
ジェネリック aliastype Pair<A, B> = [A, B];
ジェネリッククラスclass Stack<T> { items: T[] = []; }
extends で制約function len<T extends { length: number }>(x: T) { return x.length; }
デフォルトの型パラメータinterface Box<T = string> { value: T; }
keyof 演算子type K = keyof User; // "id" | "name"
インデックスアクセス型type Name = User["name"];

絞り込み (Narrowing)

ユニオンを実行時に単一の型に絞り込む。

操作構文
typeof チェックif (typeof x === "string") { … }
instanceof チェックif (e instanceof Error) { … }
in 演算子if ("name" in obj) { … }
等値による絞り込みif (status === "done") { … }
真偽値による絞り込みif (value) { … }
カスタム type guardfunction isUser(x: any): x is User { return "id" in x; }
判別ユニオンtype Shape = { kind: "sq"; size: number } | { kind: "ci"; r: number };
never で網羅性チェックconst _: never = shape;

Enum

名前付き定数の集合。

操作構文
数値 enumenum Direction { Up, Down, Left, Right }
文字列 enumenum Status { Idle = "IDLE", Done = "DONE" }
値を使うlet d: Direction = Direction.Up;
const enum (インライン化)const enum Color { Red, Green, Blue }
リテラルのユニオン (モダン)type Status = "idle" | "done";

ユーティリティ型

既存の型を変換する組み込みヘルパー。

操作構文
すべてオプショナルにPartial<User>
すべて必須にRequired<User>
すべて readonly にReadonly<User>
キーの一部だけ選ぶPick<User, "id" | "name">
1 つ以上のキーを除外Omit<User, "password">
指定キーのオブジェクトRecord<string, number>
ユニオンから除外Exclude<"a" | "b" | "c", "a">
ユニオンから抽出Extract<"a" | "b", "a" | "c">
null / undefined を除くNonNullable<string | null>
関数の戻り値型ReturnType<typeof fn>
引数のタプルParameters<typeof fn>
解決済み Promise の型Awaited<Promise<string>>

モジュール

ファイル間の import と export。

操作構文
名前付き exportexport function add(a: number, b: number) { … }
デフォルト exportexport default class User { … }
再 exportexport { User } from "./user";
名前付き importimport { add } from "./math";
デフォルト importimport User from "./user";
型のみ importimport type { User } from "./user";
すべてを importimport * as math from "./math";
triple-slash 参照/// <reference types="node" />

tsconfig の基本

知っておきたいコンパイラフラグ。

オプション効果
"strict": truestrict モードのチェックをすべて有効にする (推奨)。
"target": "ES2022"tsc が出力する JavaScript のバージョン。
"module": "ESNext"出力のモジュールシステム。
"moduleResolution": "bundler"モダンなバンドラと同じ解決方式。
"jsx": "react-jsx"React 17+ 向けに JSX を有効化。
"esModuleInterop": trueCommonJS からのデフォルト import が綺麗になる。
"skipLibCheck": truenode_modules の型チェックを省略 (高速化)。
"noEmit": true型チェックのみ — 出力はバンドラに任せる。

毎日のように使う TypeScript の構文を 1 ページにまとめました。この TypeScript チートシートは、基本型、インターフェース、type alias、ジェネリクス、ユニオン、絞り込み、組み込みユーティリティ型といった日常の TS のためのクイックリファレンスです。

ここに載っているのはすべて tsc でコンパイルでき、モダンな JavaScript が動く環境ならどこでも動く標準の TypeScript です。必要なものをコピーするか、TypeScript プレイグラウンドでそのまま試せます — インストール不要です。

TypeScript チートシート FAQ

この TypeScript チートシートは無料ですか?
はい。この TypeScript チートシートは完全無料で、登録も不要です。ブックマークしておいて、型・インターフェース・ユーティリティ型を確認したいときにいつでも戻ってきてください。
interface と type alias の違いは?
どちらもオブジェクトの形を表現でき、日常的な多くのケースでは入れ替え可能です。interface はファイルをまたいで再オープン・拡張できる (declaration merging) ため、ライブラリの型に便利です。type alias はユニオン・インターセクション・タプル・mapped type など、interface では表現できない形に名前を付けられます。よくある指針は: 公開オブジェクトの形には interface、ユニオン・タプル・計算した型には type を使う、というものです。
any と unknown の違いは?
any は型チェックを完全に無効化します — コンパイラはどんな操作も許可します。unknown は型安全で、使う前に (typeofinstanceof・type guard などで) 絞り込む必要があります。JSON.parsefetch のような外部由来の値には unknown を使いましょう — 使用前のバリデーションを強制できます。
TypeScript の前に JavaScript を学ぶべき?
はい。TypeScript は JavaScript の上に型システムを乗せたものなので、JS のスキルはすべて活きます。配列・オブジェクト・async/await などの基礎を固めている途中なら、JavaScript チートシートが良い出発点です。Coddy の無料 JavaScript コースも同じ範囲をインタラクティブにカバーしています。
TypeScript をオンラインで練習できますか?
はい。TypeScript プレイグラウンドを開けば、このチートシートのどのスニペットもブラウザで実行できます — インストール不要です。体系的に学びたくなったら、JavaScript のランディングから始めて、このページの型をその上に重ねていきましょう。
Coddy programming languages illustration

CoddyでTypeScriptを学ぼう

始める