TypeScript

基本型

TypeScript

number、string、boolean、tuple、enum

基本型

number、string、boolean、null、undefined

basic-types.ts typescript
// プリミティブ型
const age:    number  = 30;
const name:   string  = 'Alice';
const active: boolean = true;
const nothing: null      = null;
const undef:   undefined = undefined;

// 型推論(型注釈を省略できる)
const age = 30;      // number と推論
const name = 'Alice'; // string と推論

// 特殊型
const anything: any    = 'anything'; // 型チェック無効化(避けるべき)
const unknown:  unknown = getData();  // 型確認してから使う(any より安全)
const nothing:  never   = (() => { throw new Error(); })(); // 到達不可能
const voidFn:   void    = undefined;  // 戻り値なしの関数

// リテラル型
const dir: 'left' | 'right' = 'left';
const code: 200 | 400 | 404 | 500 = 200;

// BigInt / Symbol
const big: bigint = 9007199254740991n;
const sym: symbol = Symbol('unique');

配列とタプル

Array、ReadonlyArray、タプル型

arrays.ts typescript
// 配列
const nums:  number[]      = [1, 2, 3];
const strs:  Array<string> = ['a', 'b'];
const mixed: (string | number)[] = [1, 'two', 3];

// 読み取り専用配列
const frozen: ReadonlyArray<number> = [1, 2, 3];
const frozen: readonly number[] = [1, 2, 3];
// frozen.push(4); // ❌ エラー

// タプル型(固定長・順序固定)
const point: [number, number] = [10, 20];
const entry: [string, number] = ['Alice', 30];

// オプショナルタプル要素
const opt: [string, number?] = ['Alice'];

// ラベル付きタプル
const rgb: [red: number, green: number, blue: number] = [255, 128, 0];

// Rest要素
const rest: [string, ...number[]] = ['sum', 1, 2, 3, 4];

// 分割代入
const [x, y] = point;
const [name, age] = entry;

Enum(列挙型)

数値・文字列・const enum

enums.ts typescript
// 数値 enum(デフォルト)
enum Direction {
    Up,    // 0
    Down,  // 1
    Left,  // 2
    Right, // 3
}
const dir: Direction = Direction.Up; // 0

// 文字列 enum(推奨 — デバッグしやすい)
enum Status {
    Active   = 'ACTIVE',
    Inactive = 'INACTIVE',
    Pending  = 'PENDING',
}
const s: Status = Status.Active; // 'ACTIVE'

// const enum(コンパイル時にインライン展開)
const enum Color {
    Red   = 0xff0000,
    Green = 0x00ff00,
    Blue  = 0x0000ff,
}
// Color.Red はコンパイル後 0xff0000 に置換

// Union型での代替(const enumより軽量)
type Direction = 'Up' | 'Down' | 'Left' | 'Right';
const dirs = ['Up', 'Down', 'Left', 'Right'] as const;
type Direction = typeof dirs[number];