4 ms·
Well, that was disappointing. I thought we left this kind of over-abstracted code behind with Java. A simple one-level switch on typeof or instanceof really do
by jahewson 9y ago
Well, that was disappointing. I thought we left this kind of over-abstracted code behind with Java. A simple one-level switch on typeof or instanceof really does not deserve to be called "pattern matching". Given that TypeScript supports tagged union types it would make far more sense to actually use them and stop using instanceof all together.
If are we going to do this kind of thing why not a least do it simply:
switch(typeof x) {
case "string":
or
switch(x.constructor)
case Thing:
Ok, so TypeScript can't handle the types for this yet but it's valid JS so you get the idea.
- masklinn 9y ago> If are we going to do this kind of thing why not a least do it simply: I expect it's because actual type-switching allows the compiler to type-assert at the same time. So it knows what within the String branch the value is an actual string. Whereas typeof() is severely limited (only primitive types) and switching on an arbitrary property tells pretty much nothing to the compiler.
- jahewson 9y agoYes, that's the current state of things. But support for control-flow typing of my above two examples seems like an easy addition to the TypeScript compiler - if that's what you want. Personally I'd like to see JS support for proper pattern matching, i.e. TC39, then TypeScript can build on that.
- masklinn 9y ago> But support for control-flow typing of my above two examples seems like an easy addition to the TypeScript compiler - if that's what you want. The first one is not useful and the second one is nonsensical (as there is no guarantee that there's any relation between #constructor and the type of the variable)