TypeScriptの書き方
よく使う文法・タグ・操作を、短い例で。42項目から探せます。
42 / 42項目
型チェックはstrict設定を想定しています。実行前にJavaScriptへ変換します。
基本の型
入れてよい値の種類を、コードで伝えます。
const name: string = "海";
const age: number = 20;
console.log(name);関数の型
受け取る値と、返す値を決めます。
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3));オブジェクトの型
ひとまとまりの情報にも、形を決められます。
type User = { name: string };
const user: User = { name: "海" };
console.log(user.name);配列の型
一覧に入る値の種類をそろえます。
const names: string[] = ["海", "空"];
console.log(names[0]);ユニオン型
いくつかの選択肢を持つ値を表します。
type Color = "red" | "blue";
const color: Color = "red";省略できる項目
必須ではない情報を、?で表します。
type User = { nickname?: string };
const user: User = {};
console.log(user.nickname ?? "名無し");型を絞り込む
値の種類を調べて、安全に処理します。
function show(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
show("hello");型の推論
値から型が決まる。
let age = 20;
age = 21;
// age = "海"; は型エラーboolean・null・undefined
真偽値や値のない状態を表す。
const active: boolean = true;
const name: string | null = null;
const value: number | undefined = undefined;リテラル型
決まった値だけを許可する。
let size: "small" | "large" = "small";interface
オブジェクトの形に名前を付ける。
interface User {
name: string;
age: number;
}
const user: User = { name: "海", age: 20 };readonly
型チェックで書き換えを禁止する。
type User = { readonly id: number };
const user: User = { id: 1 };
// user.id = 2; は型エラー実行時に値を凍結する機能ではありません。
タプル
位置ごとの型と長さを決める。
const pair: [string, number] = ["海", 20];unknown
型を調べるまで操作できない値。
const value: unknown = "海";
if (typeof value === "string") {
console.log(value.length);
}any
型チェックを避ける。
let value: any = "海";
value = 20;誤りを見つけにくくなるため、まずunknownなどを検討します。
型アサーション
値の型についてコンパイラーに伝える。
const input = document.querySelector("input") as HTMLInputElement | null;
console.log(input?.value);asは値を変換しません。実際の型が違っていても検証しません。
as const
値をリテラルとして固定した型にする。
const colors = ["red", "blue"] as const;satisfies
値が型に合うか確認する。
type User = { name: string };
const user = { name: "海" } satisfies User;省略できる引数
引数を省略可能にする。
function greet(name?: string): string {
return name ?? "ゲスト";
}関数そのものの型
受け取る値と返す値を指定する。
const add: (a: number, b: number) => number =
(a, b) => a + b;void・never
返り値なし、または正常に戻らない関数。
function log(): void { console.log("海"); }
function fail(): never { throw new Error("失敗"); }ジェネリクス
受け取った型を結果にも引き継ぐ。
function first<T>(items: T[]): T | undefined {
return items[0];
}
const name = first(["海", "空"]);型の制約
受け取れる型に条件を付ける。
function getName<T extends { name: string }>(user: T) {
return user.name;
}交差型
複数の型の条件を合わせる。
type Name = { name: string };
type Age = { age: number };
type User = Name & Age;判別可能なユニオン
共通の目印で型を分ける。
type Result =
| { ok: true; value: string }
| { ok: false; error: string };
function show(r: Result) {
if (r.ok) console.log(r.value);
}inによる絞り込み
項目があるか調べて型を区別する。
function show(value: { name: string } | { age: number }) {
if ("name" in value) console.log(value.name);
}keyof
型のプロパティ名を型にする。
type User = { name: string; age: number };
type UserKey = keyof User; // "name" | "age"typeofによる型取得
既存の値から型を作る。
const settings = { dark: true };
type Settings = typeof settings;インデックスアクセス型
プロパティや配列の要素の型を取り出す。
type User = { name: string };
type Name = User["name"];
type Item = string[][number];Partial
すべての項目を省略可能にする。
type User = { name: string; age: number };
const update: Partial<User> = { age: 21 };Required
すべての項目を必須にする。
type User = { name?: string };
const user: Required<User> = { name: "海" };Pick
必要な項目だけ選ぶ。
type User = { name: string; age: number };
type NameOnly = Pick<User, "name">;Omit
指定した項目を除く。
type User = { name: string; age: number };
type WithoutAge = Omit<User, "age">;Record
キーと値の型を決める。
const prices: Record<string, number> = {
apple: 100, orange: 200
};Readonly
すべての項目を書き換え禁止にする。
type User = { name: string };
const user: Readonly<User> = { name: "海" };Exclude・Extract
候補を除く、または共通候補を選ぶ。
type Color = "red" | "blue" | "green";
type Other = Exclude<Color, "red">;
type Warm = Extract<Color, "red" | "orange">;NonNullable
nullとundefinedを除く。
type Name = string | null | undefined;
type PresentName = NonNullable<Name>;ReturnType・Parameters
関数から返り値や引数の型を取り出す。
function add(a: number, b: number) { return a + b; }
type Answer = ReturnType<typeof add>;
type Args = Parameters<typeof add>;Promiseの型
非同期処理の結果の型を示す。
async function greet(): Promise<string> {
return "こんにちは";
}型だけのimport・export
型を別ファイルへ分ける。
// user.ts
export type User = { name: string };
// app.ts
import type { User } from "./user";interfaceの継承
既存の型に項目を足す。
interface User { name: string; }
interface Admin extends User { role: string; }クラスの型
プロパティと引数に型を付ける。
class User {
constructor(public name: string) {}
greet(): string { return this.name; }
}