typeof true === "boolean"
To me, the above line of code is prone to bugs because the string "boolean" can easily be misspelled:
typeof true === "Boolean"
So there has to be a better, built-in, function to do this.
CodePudding user response:
You could compare with typeof true
.
if(typeof someVar === typeof true){
}
CodePudding user response:
I suppose you could compare against the two possible values:
if (someVal === true || someVal === false)
which will throw a ReferenceError if you've misspelled one of them - but other than that, JavaScript doesn't really have the sort of strict-ness you're looking for.
This is one of the situations in which I'd highly recommend TypeScript, which will indeed warn you against doing such a thing (and will also warn you against many other type-related errors that are easy to make):
const someBool = Math.random() < 0.5 ? '123' : true;
if (typeof someBool === 'boolea') {
}
throws
This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"boolea"' have no overlap.
I consider TypeScript to be essential for any reasonable-sized script because of the many possible mistakes it guards against - it can turn annoying or hard-to-debug runtime errors into trivially fixable compile-time errors.
CodePudding user response:
I use this snippet in my code
// Type checker function
const isType = (type, val) => !!(val.constructor && val.constructor.name.toLowerCase() === type.toLowerCase());
// Tests
console.log(isType("array", []));
console.log(isType("object", {}));
console.log(isType("regexp", new RegExp("foobar")));
console.log(isType("BOOlean", false));
// Last is false
console.log(isType("string", []));
CodePudding user response:
As mentioned by the others, compile-time checking (e.g. TypeScript) is the best way to validate strings written in source code (because the validation happens before runtime, and because it adds no performance penalty to your execution). However, if you're looking for a purely runtime solution that will throw an error if you type an invalid string into your code, you could use something like this:
const types = new Set([
'bigint',
'boolean',
'function',
'number',
'object',
'string',
'symbol',
'undefined',
]);
function isType (type, value) {
if (!types.has(type)) throw new TypeError(`Invalid type: "${type}"`);
return typeof value === type;
}
// example
console.log(isType('boolean', true)); //=> true
console.log(isType('boolean', false)); //=> true
console.log(isType('boolean', 'hello')); //=> false
console.log(isType('Boolean', true)); //=> TypeError