hd-utils
Version:
A handy utils for modern JS developers
35 lines (34 loc) • 1.17 kB
JavaScript
/**
* Tests for one of the [`Primitive`](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) types using the JavaScript [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) operator
*
* Clarification: TypeScript overloads this operator to produce TypeScript types if used in context of types.
*
* @param val The value to be tested
* @returns If `val` is primitive. If used in the flow of the program typescript will infer type-information from this.
*
* @example
* const consumer = (value: Primitive | Primitive[]) => {
* if (isPrimitive(value)) {
* return console.log('Primitive value: ', value);
* }
* // type of value now inferred as Primitive[]
* value.map((primitive) => consumer(primitive));
* };
*/
const isPrimitive = (val) => {
if (val === null || val === undefined) {
return true;
}
switch (typeof val) {
case 'string':
case 'number':
case 'bigint':
case 'boolean':
case 'symbol': {
return true;
}
default:
return false;
}
};
export default isPrimitive;