チュートリアル

TypeScript基礎:はじめてのTypeScript

TypeScript入門型システム
広告エリア

はじめに

TypeScriptはJavaScriptに静的型付けを追加した言語です。コンパイル時に型エラーを検出でき、大規模開発に適しています。

環境構築

# Node.jsがインストールされている前提
npm install -g typescript

# バージョン確認
tsc --version

# コンパイル
tsc file.ts

# プロジェクト初期化
tsc --init

基本的な型

プリミティブ型

// 文字列
const name: string = "太郎";

// 数値
const age: number = 25;

// 真偽値
const isActive: boolean = true;

// null と undefined
const n: null = null;
const u: undefined = undefined;

// シンボル
const sym: symbol = Symbol("id");

// bigint
const big: bigint = 100n;

配列

// 配列
const numbers: number[] = [1, 2, 3];
const strings: Array<string> = ["a", "b", "c"];

// タプル(固定長・固定型の配列)
const tuple: [string, number] = ["太郎", 25];
const [name, age] = tuple;

// 読み取り専用
const readonlyArr: readonly number[] = [1, 2, 3];
// readonlyArr.push(4);  // エラー

オブジェクト

// オブジェクト型
const user: { name: string; age: number } = {
  name: "太郎",
  age: 25
};

// オプショナルプロパティ
const user2: { name: string; email?: string } = {
  name: "花子"
};

// 読み取り専用
const config: { readonly apiKey: string } = {
  apiKey: "abc123"
};
// config.apiKey = "xyz";  // エラー

型推論

TypeScriptは型を自動的に推論します。

// 型注釈なしでも型が推論される
let message = "Hello";  // string型と推論
let count = 10;         // number型と推論
let items = [1, 2, 3];  // number[]型と推論

// 推論できない場合は明示的に
let data: string | number;
data = "hello";
data = 42;

関数の型

// 引数と戻り値の型
function add(a: number, b: number): number {
  return a + b;
}

// アロー関数
const multiply = (a: number, b: number): number => a * b;

// 戻り値なし
function log(message: string): void {
  console.log(message);
}

// オプショナル引数
function greet(name: string, greeting?: string): string {
  return `${greeting ?? "こんにちは"}, ${name}!`;
}

// デフォルト引数
function greet2(name: string, greeting: string = "こんにちは"): string {
  return `${greeting}, ${name}!`;
}

// 残余引数
function sum(...numbers: number[]): number {
  return numbers.reduce((acc, n) => acc + n, 0);
}

関数型

// 関数型の定義
type AddFunction = (a: number, b: number) => number;

const add: AddFunction = (a, b) => a + b;

// コールバック関数
function doSomething(callback: (result: string) => void): void {
  callback("完了");
}

ユニオン型とリテラル型

// ユニオン型(複数の型のいずれか)
let id: string | number;
id = "abc";
id = 123;

// リテラル型(特定の値のみ)
let direction: "north" | "south" | "east" | "west";
direction = "north";
// direction = "up";  // エラー

// ユニオン型とリテラル型の組み合わせ
type Status = "pending" | "approved" | "rejected";
function updateStatus(status: Status): void {
  console.log(status);
}

型エイリアス

// 型に名前をつける
type UserId = string;
type Point = { x: number; y: number };

const userId: UserId = "user-123";
const point: Point = { x: 10, y: 20 };

// 複雑な型の整理
type User = {
  id: UserId;
  name: string;
  email: string;
  createdAt: Date;
};

インターフェース

interface User {
  id: string;
  name: string;
  email: string;
}

const user: User = {
  id: "1",
  name: "太郎",
  email: "taro@example.com"
};

// 拡張
interface Employee extends User {
  department: string;
  salary: number;
}

// メソッド
interface Calculator {
  add(a: number, b: number): number;
  subtract(a: number, b: number): number;
}

type vs interface

// interface - 拡張可能、オブジェクト型向け
interface Animal {
  name: string;
}
interface Dog extends Animal {
  breed: string;
}

// type - ユニオン型、プリミティブ、タプルなど
type ID = string | number;
type Pair = [string, number];
type Status = "active" | "inactive";

// 一般的な使い分け
// - オブジェクトの形状 → interface
// - ユニオン型、タプル → type

any と unknown

// any - 型チェックを無効化(非推奨)
let anything: any = "hello";
anything = 42;
anything.foo.bar;  // エラーにならない(危険)

// unknown - 安全なany
let something: unknown = "hello";
something = 42;
// something.foo;  // エラー(型を確認するまで使えない)

if (typeof something === "string") {
  console.log(something.toUpperCase());  // OK
}

型アサーション

// 型を明示的に指定
const input = document.getElementById("input") as HTMLInputElement;
input.value = "hello";

// 別の構文(JSXと競合するため非推奨)
const input2 = <HTMLInputElement>document.getElementById("input");

// 非nullアサーション
const element = document.getElementById("app")!;  // nullではないと断言

まとめ

  • TypeScriptはJavaScriptに型を追加した言語
  • 基本型: string, number, boolean, null, undefined
  • 配列: number[] または Array<number>
  • 関数: 引数と戻り値に型をつける
  • typeinterfaceで独自の型を定義
  • anyは避けてunknownを使う

次回は高度な型について学びます。

広告エリア