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?

More than 1 year has passed since last update.

TypeScriptの型定義時に使用する「?」

Last updated at Posted at 2023-06-10

疑問

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

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?