EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript type check
Secondary Sidebar
TypeScript Tutorial
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript type check

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.

Before getting into syntax, we need to first install the library type-check using npm.
Installation Command: This command is available through NPM.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - 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

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*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?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more