2
2

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】typeとclassの使い分け

Last updated at Posted at 2025-03-26

TypeScriptでデータの型を表現するとき、「type」と「class」のどちらを使うか迷ったので、ざっくり定義しつつまとめました。

typeとは

型エイリアスを宣言する際に必要なキーワードです。

  • データの「形(構造)」だけを定義するもの
  • 実行時には存在しない(コンパイル時だけ使われる)
  • メソッド(処理)は持たない

型エイリアスとは

型に「名前をつける」ための仕組み
データを何度も使いたい時に名前をつけて再利用して使います
種類はこんな感じです

// プリミティブ型
type Str = string;
// リテラル型
type OK = 200;
// 配列型
type Numbers = number[];
// オブジェクト型
type UserObject = { id: number; name: string };
// ユニオン型
type NumberOrNull = number | null;
// 関数型
type CallbackFunction = (value: string) => boolean;

プリミティブ型:string や number 単体で表す
リテラル型:特定の値だけを許したいとき(例:HTTPステータスコード)
ユニオン型:2つ以上の型のどれかになる可能性があるとき
関数型:関数を型として扱うとき

classとは

クラスはオブジェクトの雛形を定義したものです。

  • 実体(インスタンス)を作るための設計図
  • プロパティ(データ)とメソッド(処理)を持てる
  • 実行時にも存在し、オブジェクトとして振る舞う
  • クラスに対してnewキーワードを使うと、オブジェクトを生成できる
export class Record {
  constructor(
    public id: string,
    public title: string,
    public time: string,
    public created_at: string
  ) {}

  // 日付を整形するなどのメソッドも追加できる
  getFormattedDate(): string {
    const date = new Date(this.created_at);
    return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  }
}

どう使い分けるのか

今回のユースケースは、入力フォームから取得したデータをSupabaseにそのまま送るだけでした。その際にclassかtypeで迷ったのですが、
「new で作らない」し、「メソッドもいらない」なら type がちょうどいいという判断してtypeを使いました。

まとめ

  • データの形だけ伝えたい → type
  • 実体を操作・変換したい → class

関連リンク

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?