LoginSignup
1
1

More than 1 year has passed since last update.

仕様の曖昧さをカバーしていたらnullチェックで型から追放されてしまったnullability。いまさら帰ってこいと言われてももう遅い

Last updated at Posted at 2021-06-28

Narrowing(型の絞り込み)の話です。この記事で言いたかった事はもう全て言い終えました。残りは雑談コーナーです。

  const narou = (message: string | null) => {
    if (message === null) {
      throw new Error('もう遅い')
    }
    return message
  }
  type NarouReturnType = ReturnType<typeof narou>

こういう時にNarouReturnTypeはstring | nullからstringへNarrowingされます。

  const narou = (message: { type: string | null; body: string }) => {
    if (message.type === null) {
      throw new Error('もう遅い')
    }
    return message
  }
  type NarouReturnType = ReturnType<typeof narou>

でもこの場合NarouReturnTypeは{ type: string; body: string }になってくれたりはしません。{ type: string | null; body: string }のままです。あくまで親オブジェクトの型としては1つなので子が絞り込まれようともそれによって新しい型は作ってくれないという事でしょうかね。親子といえど所詮他人。

  const narou = (message: { type: string | null; body: string }) => {
    if (message.type === null) {
      throw new Error('もう遅い')
    }
    return { ...message, type: message.type }
  }
  type NarouReturnType = ReturnType<typeof narou>

こうするとNarouReturnTypeは{ type: string; body: string }になってくれます。実装としても新しいオブジェクトを生成しているので、よろしい新しい型を作ってやろうという事でしょうか。

  const narou = (message: { type: string; body: string } | { type: null; body: string }) => {
    if (message.type === null) {
      throw new Error('もう遅い')
    }
    return message
  }
  type NarouReturnType = ReturnType<typeof narou>

なおこの場合もNarrowingされます。以上、TS4.2.4からでした。

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