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?

ちょっと深堀りTypeScript

Posted at
1 / 11

はじめにはっきりしておきたいこと

  • 私のスタンス:型のある言語が大好き
  • 関数を作るとき、まず型を書いて具体的なコーディングに入るタイプ

TypeScriptとは

  • TypeScriptは「型のあるJavaScript」
  • 特に嬉しいのがnullやundefinedの悪影響が緩和されること

JavaScriptの危ない例

function firstElement(ary) {
  ...
}

配列の先頭要素を返す関数。配列の要素数が0の場合はどうなる?
→ 例外がスローされる?それともnullが返る?それともundefined?


TypeScriptによる改善

function firstElement<E>(ary: E[]): E {
  ...
}

この場合、要素数が0だと例外がスローされると推測できる。


function firstElement<E>(ary: E[]): E | undefined {
  ...
}

この書き方だと、要素数が0だとundefinedが返ると推測できる。


更に大事なこと!

function firstElement<E>(ary: E[]): E {
  if (ary.length === 0) {
    return undefined;
  } else {
    return ary[0];
  }
}

こう書くとコンパイルエラーになります
→ 関数の宣言ではundefinedを返すことになっていないのに、undefinedを返そうとしているから。


JavaScriptの怖いところ

  • 無意識にundefinedの可能性のあるコードを書いてしまうことは非常によくあります。
    これを防げるだけでもTypeScriptを導入する価値があります。

他のありがたい機能

  • interface:プロパティの名前と型を明示できる
    JSでプロパティの有無が原因でバグを仕込んでしまうのは非常によくあります。

TypeScriptの闇

  • interfaceはありがたい一方、JSで便利に書いていたデータ操作がやりにくくなり、大きなストレスとなることがあります。
  • そもそも型にはストレスになりがちな要素が多くあります。これは否定できないです。。。

最後に:TypeScriptを使い始めてみるなら

  • nullやundefinedを厳密に扱ってみる
  • interfaceを使ってみる

この2つだけでも、価値が高いと思います!

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?