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を書いていますが、そもそも型があったらなにが嬉しいんだったっけ?ということを、原点に戻って振り返ってみます。
この記事では、JavaScriptのコードにTypeScriptで型をつけると具体的に何が変わるのかを3つの例とともに紹介します。

関数に想定外の値を渡すことを防げる

次のJavaScriptの関数は、引数を2倍にして返します。

function double(value) {
  return value * 2;
}

console.log(double(5)); // 10
console.log(double("hello")); // NaN

double("hello") は文字列を渡しているので、結果は NaN になります。JavaScriptではこのコードはエラーになりませんが、TypeScriptでは引数に型を指定すると、書いた時点でエラーになります。

function double(value: number): number {
  return value * 2;
}

double(5);
double("hello"); // Argument of type 'string' is not assignable to parameter of type 'number'.

value: number と書くだけで、数値以外を渡そうとした箇所をエディタが指摘してくれます。

プロパティ名のtypoを検出できる

JavaScriptでは、存在しないプロパティにアクセスしても undefined が返るだけで、エラーにはなりません。

const user = {
  name: "Alice",
  age: 25,
};

console.log(user.naem); // undefined

namenaem とtypoしていますが、JavaScriptはこれを undefined にするため、見落としてしまう可能性があります。

TypeScriptでは、オブジェクトの型情報をもとにtypoを検出できます。

const user = {
  name: "Alice",
  age: 25,
};

console.log(user.naem); // Property 'naem' does not exist on type '{ name: string; age: number; }'.

戻り値の undefined を見落とさなくなる

JavaScriptでは以下のようなコードの場合、findUser(3) は該当するユーザーがいないため undefined を返しますが、呼び出し側では user.name と書いてしまい、実行時にエラーになります。

function findUser(id) {
  const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
  ];
  return users.find((u) => u.id === id);
}

const user = findUser(3);
console.log(user.name); // Cannot read properties of undefined

Array.prototype.find の戻り値は T | undefined です。 TypeScriptはこれを知っているので、userundefined かもしれないことを指摘してくれます。

type User = {
  id: number;
  name: string;
};

function findUser(id: number): User | undefined {
  const users: User[] = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
  ];
  return users.find((u) => u.id === id);
}

const user = findUser(3);
console.log(user.name); // 'user' is possibly 'undefined'.

これによって、呼び出し側で undefined チェックを書き忘れることを防げます。

const user = findUser(3);
if (user) {
  console.log(user.name);
}

まとめ

  • TypeScriptの型があると、関数に想定外の値を渡すミスを書いた時点で検出できる
  • オブジェクトのプロパティ名のタイポも、型情報があればエディタが指摘してくれる
  • 関数の戻り値に 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?