2
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】 Parameter Propertieを使ってclass作成を効率化する

Posted at

はじめに

TypeScriptのクラス作成を学習していて、Parameter Propertiesという機能を知りました。従来のクラス定義方法と比較し、Parameter Propertiesの利点を備忘録としてまとめます。

クラス(class)定義作成方法

フィールド定義+コンストラクタでフィールドを初期化

クラス内で以下の定義を行います。
・ フィールド
・ コンストラクタ

実際にクラスからオブジェクトを作成する場合(インスタンス化)、引数に値を設定することで作成可能です。

todo.ts
export class Todo {
  // フィールド定義
  public id: number;
  public title: string;
  public done: boolean;
  public created_at: string;

  // コンストラクタ
  constructor(id: number,  title: string, done: boolean, created_at: string) {
    this.id = id;
    this.title = title;
    this.done = done;
    this.created_at = created_at;
  }
}

// インスタンス化
const newTodo = new Todo(1, "title", true, "20250330");
console.log('newTodoだよ', newTodo);

image.png

個人的に感じたフィールド定義でクラス定義した場合のメリット・デメリット
メリット:フィールドを最初に定義するので、どの値を定義したクラスかわかりやすい
デメリット:冗長する

Parameter Propertiesで定義する

コンストラクタの引数に、アクセス修飾子をつけることで、フィールドを自動で定義してくれます。
TypeScriptのParameter Propertiesという機能を使うことで冗長化しない

todo.ts
// クラスの作成
export class Todo {
  constructor(
    public id: number,
    public title: string,
    public done: boolean,
    public created_at: string,
  ){}
}

// インスタンス化
const newTodo = new Todo(1, "title", true, "20250330");
console.log('newTodoだよ', newTodo);

おわりに

Parameter Propertiesの定義方法は最初どういこと?となりました。
使い方を理解した後はこちらのほうが簡潔でわかりやすく記載できるなと感じました。

参考

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