TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Pattern Matching Custom Data Types in TypeScript

42 pointsby destedover 6 years ago

7 comments

sfvisserover 6 years ago
It&#x27;s a neat trick and I&#x27;ve used similar patterns in some of our projects, but in the end it doesn&#x27;t buy you much over a `switch (x.kind) { ... }`. (Except your matcher can be used as a proper expression which is nice obviously)<p>But you don&#x27;t have proper pattern nesting, fall-through semantics and it&#x27;s not clear (to me yet) how to extend to matching on multiple values. Try implementing an equality function on a sum-type using pattern matching.<p>Having actual proper pattern matching added to TS would be such a great addition. Especially with full support of the control flow analysis.
评论 #19065851 未加载
maxxxxxover 6 years ago
I think the code is way too verbose. One supposed advantage of FP languages is that they are more concise. If I have to build a ton of boilerplate I might just as well go to some OOP pattern with interfaces and so on.
评论 #19065835 未加载
swissmanuover 6 years ago
i did an article about quite a similar solution approach some time ago: <a href="https:&#x2F;&#x2F;pattern-matching-with-typescript.alabor.me&#x2F;" rel="nofollow">https:&#x2F;&#x2F;pattern-matching-with-typescript.alabor.me&#x2F;</a><p>having real pattern matching built in to TS would be awesome. nice write up though!
评论 #19066116 未加载
Tareanover 6 years ago
Since typescript is compiled anyway it feels somewhat silly not to have the compiler do this work. I wonder how hard it would be to make the desugaring extensible, maybe with a rewrite engine like what Hermit does in haskell.
mattigamesover 6 years ago
I&#x27;m disappointed in TypeScript not having pattern matching, multiple classes inheritance, and operator overloading (a MUST for game development)
评论 #19067615 未加载
PudgePacketover 6 years ago
Don&#x27;t think the &quot;never&quot; default arm is necessary. If the return type is set and you miss a case TS should complain.
jaunkstover 6 years ago
You could use a typescript decorator to make it less verbose to setup I suppose. I would rather have a more native approach.
评论 #19066142 未加载
评论 #19066137 未加载