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 Pattern Matching
 

TypeScript Pattern Matching

Updated April 5, 2023

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.

Watch our Demo Courses and Videos

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

Syntax:

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

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