Share your repls and programming experiences

← Back to all posts
TS Pattern Example
dustinknopoff (1)

Simple example of using ts-pattern for pattern matching in typescript

Comments
hotnewtop
Coder100 (17018)

Wow! Is this like the typescript version of rust's?

let var: u32 = 5;
match var {
  1 => println!("one"),
  2 => println!("two"),
  3 | 4 => println!("three or four"),
  5 => println!("five"),
  _ => println!("idk")
}
dustinknopoff (1)

@Coder100 Yeah! I'm not the author of the library. But I'm a big fan of rust (especially pattern matching) and for work I've been using typescript. We currently use an absolute mess of typeofs, casting, and checking the type field on our objects. Decided to go scavenging on GitHub for something like rust and this is what I've found that's:
1. Recently made
2. tested
3. Actually has version numbers
4. 0 dependencies!
5. Doesn't require you to specify objects in a custom way.

Github Link

Coder100 (17018)

although I guess in a language like javascript, pattern matching is comparable to switch case it's still really cool to see ideas from other languages coming to javascript!! @dustinknopoff

dustinknopoff (1)

@Coder100 Right. but switch statements in javascript can't have additional conditional logic, i.e.

In the repl I posted, I could check the value of isyoutube in addition to type in a single case.

With a switch statement, I'd have to have an if/else block within case "video". Which is fine, but I find less readable.