You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hey, I was thinking of implementing pattern matching myself when I stumbled upon your wonderful project. Very cool. And I'm hoping it'll save me from having to roll out my own thing, if I even have enough drive to do it 😁. Now...
Given this:
abstractclassOption<T>{constructor(protectedvalue: T){}// bunch of methods}classSome<T>extendsOption<T>{constructor(value: T){super(value)}}classNoneextendsOption<void>{constructor(value: T){super(value)}}
Using ts-pattern, how do I do something functionally equivalent to this:
constsomething=newSome(Math.random());constnothing=newNone();constsomethingOrNothing=()=>Math.random()>0.5 ? something : nothing;match(somethingOrNothing()).with(newSome(select('value'),(value)=>`OMG it matched and the value is ${value}`).with(newNone(),()=>'Nothing to see here').exhaustive()// ormatch(somethingOrNothing()).with(newSome(__),()=>`OMG it matched and I don't care about the value`).with(newNone(),()=>'Nothing to see here').exhaustive()// or match(somethingOrNothing()).with(newSome(0.7)),()=>`OMG I can't believe I guessed the number`).with(newSome(__),=>`The value is something else than 0.7`).with(newNone(),()=>'Nothing to see here').exhaustive()
I think you get what I'm trying to do. The same kind of pattern matching that you would do on Result and Option types in rust. I've used a class hierarchy here but if it helps in any way, I could do this instead:
interface Option<T> {
// bunch of methods
}
class Some<T> implements Option<T> {
constructor(private value: T) {}
// bunch of methods
}
class None implements Option<void> {
// bunch of methods
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hey, I was thinking of implementing pattern matching myself when I stumbled upon your wonderful project. Very cool. And I'm hoping it'll save me from having to roll out my own thing, if I even have enough drive to do it 😁. Now...
Given this:
Using ts-pattern, how do I do something functionally equivalent to this:
I think you get what I'm trying to do. The same kind of pattern matching that you would do on Result and Option types in rust. I've used a class hierarchy here but if it helps in any way, I could do this instead:
Beta Was this translation helpful? Give feedback.
All reactions