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 5 years have passed since last update.

Typescriptで極力undefinedを書かない方法

Last updated at Posted at 2020-01-10

はじめに

Typescriptで未定義になる可能性のある変数や戻り値にundefinednullを出来るだけ割り当てたくないって話。

注: users.findは見つからなかった場合、undefinedを返すとします。

function getUser(id: number): User | undefined {
  return users.find(v => v.id === id);
}

const a = getUser(1);

// しばらくのち
if (a) {...} // 'boolean'か'undefined'か'null'か曖昧

a.name // <- ガード忘れもあるよ

通常、このようにundefinednullを返さざるをえないパターンってあると思いますが、これが長い式の間に入っていたりすると文脈上、正に不明な値になってしまったりするわけです。

という訳で一工夫してみます。

一工夫

function getUser(id: number): { ['*']?: User } {
  const maybeUser = users.find(v => v.id === id);
  
  return maybeUser ? { ['*']: maybeUser } : {}
}

const a = getUser(1)

if (a['*']) {...} // 主張感あると思いません?

a.name // <- コンパイルが通らない

a['*'].name // <- こんなガード忘れしないでしょ

これで戻り値は{ ['*']: value }{}のいずれかになり、文脈上でもしっかり主張してくれます。

['*']が気持ち悪かったら何でも良いです。個人的にピンとくる名前がなかったので記号にしちゃえってだけなので・・・。

参考

TypeScript Deep Dive 日本語版 NullとUndefined: https://typescript-jp.gitbook.io/deep-dive/recap/null-undefined

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?