こんにちは。KOUKIです。
最近、TypeScriptを学んでいますが、JavaScriptの型チェックが面白そうだったので、記事にしてみました。
型チェック – typeof演算子を使う
JavaScriptの「typeof」演算子を使うと型チェックが出来ます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Truck { drive() { console.log("driving...."); } } function goDrive(arv) { // number型 if (typeof arv === "number") { if (arv >= 18) { console.log("OK Driving!!!"); } else { console.log("No Driving!!!"); } } // string型 if (typeof arv === "string") { console.log(`${arv} is driving!!!`); } // object型 if (typeof arv === "object") { arv.drive(); } } goDrive(18); goDrive("Harry"); const truck = new Truck(); goDrive(truck); |
typeofでは、上記のようにJavaScriptの基本データ型をチェックできます。
しかし、objectに関しては、完全ではありません。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Truck { drive() { console.log("driving...."); } } class Boat { row() { console.log("rowing..."); } } function goDrive(arv) { // object型 if (typeof arv === "object") { arv.drive(); } } const boat = new Boat(); // driveを持っていないオブジェクトを渡す goDrive(boat); // => index.js:16 Uncaught TypeError: arv.drive is not a function |
上記のようにdriveメソッドを持っていないBoatクラスのオブジェクトを渡すとエラーになります。
1 |
index.js:16 Uncaught TypeError: arv.drive is not a function |
型チェック – instanceof演算子を使う
オブジェクトを型チェックする別の方法として「instanceof」演算子があります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class Truck { drive() { console.log("driving...."); } } class Boat { row() { console.log("rowing..."); } } function goDrive(arv) { // object型 if (arv instanceof Truck) { arv.drive(); } if (arv instanceof Boat) { arv.row(); } } const truck = new Truck(); goDrive(truck); // => driving... const boat = new Boat(); goDrive(boat); // => rowing... |
上記の通り、instanceofは渡されたオブジェクトのクラスを判定できます。
これはなかなか便利ですね。
TypeScriptを活用するときに重宝しそうです。
型チェック – in演算子を使う
最後の型チェックとして、「in」演算子を紹介します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Truck { drive() { console.log("driving...."); } } class Boat { row() { console.log("rowing..."); } } function goDrive(arv) { // object型 if ("drive" in arv) { arv.drive(); } if ("row" in arv) { arv.row(); } } const truck = new Truck(); goDrive(truck); // => driving... const boat = new Boat(); goDrive(boat); // => rowing... |
これも便利ですね。
in演算子は、オブジェクトにプロパティが含まれるか否かを判定してくれるようです。
おわりに
Web業界、SIer業界問わず、JavaScriptは頻繁に使われています。
簡単に使える言語ではありますが、バグを生みやすい言語でもあるので、こういった型チェックの方法を学んで置くことは有意義だと思います^^
それでは、また!
最近のコメント