JavaScript check type of a value using check-more-types library

In this JavaScript tutorial we learn how to check the type of a value using the type() method of check-more-types module.

Create the sample project

Firstly we create an empty project with the following command.

mkdir sample-project
cd sample-project
npm init -y

And install the check-more-types module using the following command.

npm install check-more-types --save

How to check type of a value in JavaScript

To check the type of a given variable we can use the type() method of the check-more-types library.

In the sample-project directory create a new file named check-type.js as below.

check-type.js

var check = require('check-more-types');

console.log(check.type('string', 'toricode.com'));
console.log(check.type('string', 1));

console.log(check.type('number', 1));
console.log(check.type('number', 'toricode.com'));

const isString = check.type('string');
console.log(isString('toricode.com'));
console.log(isString(7));

Run the check-type.js file using the following command.

node check-type.js
The output is:
true
false
true
false
true
false

More examples of how to use the check.type() method

check-type-example.js

var check = require('check-more-types');

var value1 = 'toricode';
var value2 = 199;

if(check.type('string', value1)) {
    console.log(value1 + ' is a string.');
}

if(check.type('string', value2)) {
    console.log(value2 + ' is a string.');
}

const isNumber = check.type('number');

if(isNumber(value1)) {
    console.log(value1 + ' is a number.');
}

if(isNumber(value2)) {
    console.log(value2 + ' is a number.');
}

Run the check-type-example.js file using the following command.

node check-type-example.js
The output is:
toricode is a string.
199 is a number.

Happy Coding 😊