EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript type check
 

TypeScript type check

Updated April 10, 2023

TypeScript type check

 

 

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.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

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

install

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:

typescript 1

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:

typescript 2

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:

example 3-1

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:

typescript 3

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.

  1. TypeScript Function Interface
  2. TypeScript Optional Chaining
  3. Typescript Key-Value Pair
  4. TypeScript Set

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW