0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【エラー対処メモ】NestJSでDTOを定義した時のコンパイルエラー

0
Posted at

状況

個人開発のアプリで、新規アカウントの登録処理で使うDTOを定義したところ
フィールド名に赤線エラーが表示された
※TypeScriptはStrictモードをtrueにした状態

エラーメッセージ

プロパティ 'name' に初期化子がなく、コンストラクターで明確に割り当てられていません。
ts(2564) (property) CreateOrganizationDto.name: string

該当コード

export class CreateOrganizationDto {
  @IsString()
  @IsNotEmpty()
  name: string;
}

原因

TypeScriptのコンパイラがこのプロパティはあとで必ず初期化されると認識できていないため(コンストラクタで初期化を明示しておらず、Undefinedになる可能性があるため)

対策

必須項目には!(確実な代入アサーション)を、任意入力の項目には?(オプショナルプロパティ)をつける
NestJSではValidationPipeclass-transformerによってリクエストからバリデーションされた値がDTOに入る。
つまり、コンストラクタでは初期化されない実行時には必ず値が入るのをTypeScript側に伝える必要がある

改善後のコード

export class CreateOrganizationDto {
  @IsString()
  @IsNotEmpty()
  name!: string;
}

参考

NestJS + PrismaのPOST APIにDTOとValidationPipeを追加して入力チェックする

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?