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.
You could compare with typeof true.
if(typeof someVar === typeof true){
}
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.
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", []));