疑問
TypeScriptで型定義時に「?」を付ける場合とつけない場合があるが、違いは何か。
interface.ts
export interface Post {
id: number
title?: string
}
答え
省略可能(必須でない)プロパティのときにつける。
?のついた引数はオプション引数 (optional parameter) と呼ばれる。
オプション引数は、型とundefinedのユニオン型となる。
上記の例だと、titleは、string | undefined型になる。
おまけ
下記の書き方だと、titleはstring | undefined型となるが、省略ができないので注意。
interface.ts
export interface Post {
id: number
title: string | undefined
}
参考
https://nakagaw.hateblo.jp/entry/2018/07/11/104200
https://yukimasablog.com/typescript-optional
https://typescriptbook.jp/reference/functions/optional-parameters