JavaScriptで変数の型を調査する際よく使われる演算子に typeof というものがあります。typeof 演算子は次の様に変数のデータ型を判定することができます。
typeof – JavaScript | MDN
1 2 3 4 5 6 7 8 9 10 11 12 | // 上記 MDN ページより引用 console.log( typeof 42); // Expected output: "number" console.log( typeof 'blubber' ); // Expected output: "string" console.log( typeof true ); // Expected output: "boolean" console.log( typeof undeclaredVariable); // Expected output: "undefined" |
例にもある様に typeof 変数 === ‘string’となれば、それは文字列変数です。しかし厄介なことに typeof 変数 === ‘object’ でも文字列変数である場合があります。この記事ではその様な変数の生まれ方と、その変数が文字列であることを識別する方法について紹介します。
実際に typeof 変数 が ‘object’ になる文字列変数を生むコードが次です。
1 2 | const strObj = new String( "Hello, World!" ); console.log( typeof strObj); // 'object' |
よくある文字列を変数に代入する形でなく、Stringコンストラクタを使って文字列を作成すると、typeof演算子では’object’となってしまいます。これはStringコンストラクタで生成された変数が、実際には文字列オブジェクトであり、プリミティブ型の文字列ではないためです。
文字列オブジェクトも含めて識別するコードが次です。
1 2 3 4 5 6 7 8 9 10 | const isString = (value) => typeof value === 'string' || value instanceof String; const str = 'Hello, World!' ; console.log(isString(str)); // true const strObj = new String( 'Hello, World!' ); console.log(isString(strObj)); // true class AppString extends String {} const strMyObj = new String( 'Hello, World!' ); console.log(isString(strMyObj)); // true |
typeof で全ての文字列を包括できない原因がわかれば対策は容易です。typeof と String オブジェクトの和集合に属するか否かの判定で文字列か否かを識別できます。
この記事では String を取り上げましたが Number や Boolean でも同様のことが起き、同様の方法で識別をより正確にできます。
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 | // 数値型かチェック const isNumber = (value) => typeof value === 'number' || value instanceof Number; // 使用例 const num = 42; console.log(isNumber(num)); // true const numObj = new Number(42); console.log(isNumber(numObj)); // true class AppNumber extends Number {} const numMyObj = new AppNumber(42); console.log(isNumber(numMyObj)); // true // 真偽型かチェック const isBoolean = (value) => typeof value === 'boolean' || value instanceof Boolean; // 使用例 const bool = true ; console.log(isBoolean(bool)); // true const boolObj = new Boolean( true ); console.log(isBoolean(boolObj)); // true class AppBoolean extends Boolean {} const boolMyObj = new AppBoolean( true ); console.log(isBoolean(boolMyObj)); // true |