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

オプショナルプロパティ

TypeScript のオブジェクトの型は{<key名>: <プロパティの型>}の形で表されますが、プロパティキーの後に?をつけることでそのプロパティがあってもなくてもよいこと(オプショナルであること)を明示できます。

type Fish = {
  name: string
  age?: number
}

一方で、undefined型とのユニオン型をとることでも、プロパティがundefinedであってもよいことを明示できます。

type Fish = {
  name: string
  age: number | undefined
}

一見同じ型に思える?| undefined ですが、実はそれぞれ異なる意味を持っています。
以下で両者の違いをみていきたいと思います。

?| undefinedの違い

両者の違いは、プロパティが必須かどうかにあります。

?の場合には、オブジェクトにそのプロパティがなくても型エラーが発生しません

一方で、| undefined とした場合には、オブジェクトにそのプロパティ自体が存在している必要があります。

type Fish = {
  name: string 
  age?: number
}

type Octopus = {
  name: string
  age: number | undefined
}

const fish: Fish = {
  name: 'Tuna'
}

const octopus: Octopus = { //Property 'age' is missing in type '{ name: string; }' but required in type 'Octopus'.(2741)
  name: 'octopus'
}

undefined型とのユニオン型の場合には、値がundefinedであることは許すが、プロパティ自体が存在しないことは許さないので、プロパティ自体は持たせておきたいという場合に使用すると、型により詳細な情報を持たせられていいですね。

const octopus: Octopus = { // プロパティが揃っているので型エラーは出ない
  name: 'octopus',
  age: undefined
}
1
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
1
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?