Updated April 10, 2023
Introduction to TypeScript type check
TypeScript type check is used to validate the type of any variable at runtime. Type checking has proven to be a good feature for most JavaScript developers. We will start with the most basic library provided by TypeScript, which will directly validate the type of single variables in the code. Internally there are many types of validations involved for the Type Check Library. With a JavaScript background, type checking in TypeScript is not clearly expressed. TypeScript performs static type checking at compilation. TypeScript code when run generates a JavaScript file, which does not know anything about the types being used in the code. Let us have a wider understanding on How Type Checking works and explore few examples.
Before getting into syntax, we need to first install the library type-check using npm.
Installation Command: This command is available through NPM.
npm install type-check
Required packages have been installed in our Visual Studio Code.
Once after installation, we will use the syntax of type checking to check the variable types in TypeScript.
Syntax:
Here is the syntax ,
typeCheck(dataType, value);
This syntax receives two parameters, one is the type definition and the other is the actual value of the variable user tries to check at runtime.
For e.g. typeCheck(‘String’, ‘Hello world’);
This method will return a Boolean value ‘true’ if true and ‘false’ if false. It will check the variable with the data type parameter and return Boolean value accordingly.
Let us see a very simple and basic example of typeCheck,
Example #1: Basic typeCheck example.
import { typeCheck } from 'type-check';
console.log(typeCheck('String', 'Hello World'));
console.log(typeCheck('Number', 'educba'));
console.log(typeCheck('Number', 100));
console.log(typeCheck('Error', undefined));
console.log(typeCheck('String', 101));
console.log(typeCheck('Number', '102'));
Output:
Based on the output, String matches ‘Hello World’ and hence returns ‘true’. Number does not match ‘educba’ and returns false.
Example #2: Multiply two numbers.
import { typeCheck } from 'type-check';
function multiplyNumber(empname, emptype){
return {
empname, emptype
}
}
function empFunction(attr, fn, rtrnType){
return (...args) => {
const [x, y] = [...args]
const firstParameter = attr[0]
if(!typeCheck(firstParameter.emptype, x)) {
throw new Error("Invalid type for attribute " + firstParameter.empname + " looking for " + firstParameter.emptype )
}
const secondParameter = attr[1]
if(!typeCheck(secondParameter.emptype, y)) {
throw new Error("Invalid type for attribute " + secondParameter.empname + " looking for " + secondParameter.emptype + " but received " + (typeof y))
}
const finalValue = fn(x, y)
if(!typeCheck(rtrnType, finalValue)) {
throw new Error("Invalid type returned for function, it should be " + rtrnType)
}
return finalValue
}
}
const multiply = empFunction([multiplyNumber('x', 'Number'), multiplyNumber('y', 'Number')], (x, y) => {
return x * y
}, 'Number')
console.log(multiply(5,4))
console.log(multiply(209,'string'))
Output:
Hence the value 20 is the return type for multiply(5,4).
Above code would fail directly at the time of compilation for TypeScript. Type checks are intuitive for function instances
Example #3: TypeScript type check for array
import { typeCheck } from 'type-check';
function array(empname, emptype){
return {
empname, emptype
}
}
function empFunction(attr, fn, rtrnType){
return (...args) => {
const [x, y] = [...args]
const firstParameter = attr[0]
if(!typeCheck(firstParameter.emptype, x)) {
throw new Error("Invalid type for attribute " + firstParameter.empname + " looking for " + firstParameter.emptype )
}
const secondParameter = attr[1]
if(!typeCheck(secondParameter.emptype, y)) {
throw new Error("Invalid type for attribute " + secondParameter.empname + " looking for " + secondParameter.emptype + " but received " + (typeof y))
}
const finalValue = fn(x, y)
if(!typeCheck(rtrnType, finalValue)) {
throw new Error("Invalid type returned for function, it should be " + rtrnType)
}
return finalValue
}
}
const arraypush = empFunction([array('target', '[Number]'), array('newValue', 'Number')], (trgt, value) => {
trgt.push(value)
return trgt
}, '[Number]')
let empids = [56, 78, 90, 65, 32]
empids = arraypush(empids, 21, 78)
console.log("Array: ", empids);
arraypush(empids, 'string')
arraypush(empids, 7)
Output:
arraypush(empids, ‘string’) returned attribute error, as array values look for Numbers and not string.
Typescript type check method which we are using actually accepts an optional third argument.
Example #4: TypeScript type check with the third parameter
import { typeCheck } from 'type-check';
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function(x) {
return x % 2 === 0;
}
}
}
};
console.log(typeCheck('Even', 20, options));
console.log(typeCheck('Even', 31, options));
console.log(typeCheck('Even', 25, options));
console.log(typeCheck('Even', 33, options));;
Output:
This type of way is one of the equivalent way of defining own types in TypeScript. There is also another way to check types i.e. using Typify. It is also a library package to be installed using NPM. Command: npm install typify
Another method is to use ‘typeonly’ package by using the command: npm install typeonly, this library will be installed to check types.
Conclusion
With this we conclude our topic ‘TypeScript type check’. We have seen how TypeScript check type works along with its syntax beforehand, we have also learnt how to install the package by using NPM command. Explored various type of examples from basic to complex types. You can also check out the other two methods ‘Typify’ and ‘typeonly’ methods or libraries in checking the types in TypeScript language. Thanks! Happy Learning!!
Recommended Articles
We hope that this EDUCBA information on “TypeScript type check” was beneficial to you. You can view EDUCBA’s recommended articles for more information.