1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptの型定義について

1
Posted at

TypeScriptの型定義について、主要なものをまとめます。

基本的な型

// プリミティブ型
let str: string = "hello";
let num: number = 42;
let bool: boolean = true;
let n: null = null;
let u: undefined = undefined;
let big: bigint = 100n;
let sym: symbol = Symbol("key");

// any / unknown / never / void
let a: any = "何でもOK";
let uk: unknown = "型チェック必要";
let v: void = undefined;  // 関数の戻り値なし
function throws(): never { throw new Error(); }

オブジェクト・配列

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

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

// タプル
const tuple: [string, number] = ["hello", 42];

インターフェース・型エイリアス

// interface
interface User {
  id: number;
  name: string;
  email?: string;       // optional
  readonly role: string; // 読み取り専用
}

// type alias
type Point = {
  x: number;
  y: number;
};

// interfaceは拡張可能
interface Admin extends User {
  permissions: string[];
}

// typeは交差型で合成
type AdminUser = User & { permissions: string[] };

ユニオン・インターセクション

// ユニオン型(どちらか)
type ID = string | number;
type Status = "active" | "inactive" | "pending"; // リテラル型

// インターセクション型(両方)
type AB = { a: string } & { b: number };

ジェネリクス

// 関数
function identity<T>(arg: T): T {
  return arg;
}

// インターフェース
interface Box<T> {
  value: T;
}

// 制約付き
function getLength<T extends { length: number }>(arg: T): number {
  return arg.length;
}

ユーティリティ型

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

Partial<User>         // 全プロパティをoptionalに
Required<User>        // 全プロパティを必須に
Readonly<User>        // 全プロパティをreadonlyに
Pick<User, "id" | "name">    // 指定プロパティだけ抽出
Omit<User, "email">          // 指定プロパティを除外
Record<string, number>       // { [key: string]: number }
Exclude<"a"|"b"|"c", "a">   // → "b" | "c"
Extract<"a"|"b"|"c", "a"|"b"> // → "a" | "b"
NonNullable<string | null>   // → string
ReturnType<typeof fn>        // 関数の戻り値型
Parameters<typeof fn>        // 関数の引数型(タプル)

型ガード

// typeof
function double(x: string | number) {
  if (typeof x === "string") return x.repeat(2);
  return x * 2;
}

// instanceof
if (err instanceof Error) console.log(err.message);

// カスタム型ガード
function isUser(obj: any): obj is User {
  return typeof obj.name === "string";
}

条件型・マップ型

// 条件型
type IsString<T> = T extends string ? true : false;

// マップ型
type Optional<T> = { [K in keyof T]?: T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };

特定のトピック(ジェネリクスの深掘り、infer、テンプレートリテラル型など)について詳しく知りたい場合は聞いてください。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?