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 Pattern Matching
Secondary Sidebar
TypeScript Tutorial
  • 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
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • 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 Pattern Matching

TypeScript Pattern Matching

Introduction to TypeScript Pattern Matching

Pattern matching in TypeScript behaves the same as it does in other programming languages, there is no specific way to do it, but we have some alternative by which we can achieve pattern matching. Also, we have some of the library available for TypeScript by which we can do pattern matching because, in TypeScript, there is no built-in mechanism for pattern matching. Pattern matching is the mechanism by which we can check our passed value, whether it is correct a value the pattern is given or not.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As we already know that there is no specific way to do it, but still we have some alternative available.

1. Use switch case

switch (input) {}

2. Use Option

type Option<T> = None | Some<T>

3. Use an external library

add pattern matching package from npm.

All of these above will remove the if/else we write and make code easier to understand and readable.

How to Perform Pattern Matching in TypeScript?

As we have already seen that we do not have any built-in mechanism in TypeScript to perform pattern matching, but we have several alternatives for that. We can use functional programming with TypeScript, which supports Option, which can be used to perform pattern matching. It supports two values that are ‘None’ and ‘Some’. We have some external library available which can be used to the project by using npm, and we have to include the respective packages to use them while coding in TypeScript.

Here we will see this points in more detail with a sample example in TypeScript to see how it internally works.

1. Use External Packages

We can follow the below commands to add the packages to the application.

npm install --save pattern-matching-ts

This above command will install and save the package into the application by making an entry in the .json file.

pattern-matching-ts/lib/match

Before using them directly into the program, we have included the above package in our file. If we do not include the above package, it will give a compile-time error as we know typescript performs strict checking.

2. Use Switch Case

This is as simple and easy to use as any other programming language. We just have to supply the input here and write some case based on the condition it will match the given pattern and return us the correct result.

Example:

Code:

function demoMatchFunction(input: any): any {
switch (input) {
case 1:
return 'Hi ! I am matched !!';
case 2:
return 'Matched !!';
case 3:
return 'Matched !!!';
case 4:
return 'Matched !!!';
default:
return `${input}`;
}
}

In the above lines of code, we are creating one function which accepts any type of parameter as the input param here. Inside the function, we have written a switch statement to check whether the passed value matches with any of the statement. If it matches with any of the above statement, it will return us the value else; it will just come out.

But this has some drawbacks; also see below:

  • We have to write so many case statements, but we have only 4, but in future, something changes, and we have to add one more case, then it will fail.
  • It is not like regular expression, which can handle any type of input param and handle it.

3. Use Option

We can use Option from TypeScript, which returns two things based on the param we passed: ‘ Some’ and ‘None’.

Example:

Code:

type Option<T> = None | Some<T>

Points to remember while working with pattern matching in TypeScript:

  • TypeScript does not support any built-in function or library.
  • If we want to implement it, we can use alternatives available.
  • If they are not efficient, then we can add an external library to our application.
  • We can use the function programming option for pattern matching as well.

Example of TypeScript Pattern Matching

Given below is the example mentioned:

In this example, we are trying to implement pattern matching in TypeScript using a switch statement. We are trying to match the string here.

Code:

class DemoPattern {
demomatchfunction(input: string): string {
switch (input) {
case 'hi':
return 'Hi i am one input ';
case 'hello':
return 'Hi i am two input ';
case 'bye':
return 'Hi i am three input ';
case 'not matched':
return 'Hi i am four input ';
case 'matched':
return 'Hi i am five input ';
default:
return `${input}`;
}
}
}
console.log("Demo to show pattern matching in Typescript using switch !!");
let obj = new DemoPattern();
let result1  = obj.demomatchfunction('calling first');
let result2  = obj.demomatchfunction('hi');
let result3  = obj.demomatchfunction('hello');
let result4  = obj.demomatchfunction('matched');
let result5  = obj.demomatchfunction('I am the default one !!');
console.log("printing result !!!");
console.log("Result one is ::" + result1);
console.log("Result two is ::" + result2);
console.log("Result three is ::" + result3);
console.log("Result four is ::" + result4);
console.log("Result five is ::" + result5);

Output:

TypeScript Pattern Matching

Conclusion

Pattern matching is not easy in TypeScript because we do not have any simple way to define for it, neither we have any built-in function or library for that in TypeScript. We have to use the alternative or install and save some external library to make it work as we want. Also, we can use functional programming with TypeScript, which provides us ‘Option’ to make this work in TypeScript.

Recommended Articles

We hope that this EDUCBA information on “TypeScript Pattern Matching” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript Functions
  2. TypeScript Array
  3. TypeScript Versions
  4. What is TypeScript?
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