Type Safe Message Dispatch in TypeScript

david karapetyan on December 02, 2018

TypeScript continues to be amazing. Anders and team are doing an incredible job making the language accessible and at the same time powerful enou... [Read Full]
markdown guide
 

Thank you for a great post!
The issue I want to bring up is not specifically regarding your atricle but rather a
general Typescript issue. And I think you have a suitable pair of ears for that ;)
The code like this

switch (m.type) {
    case 'work': {
      return handlers[m.type](m);
    }
    case 'exit': {
      return handlers[m.type](m);
    }
    default: {
     const n: never = m;
     throw new Error(`This can never happen: ${n}`);
    }
  }

seems to me as a shortcoming because typescript doesn't have pattern matching which renders concepts of algebraic types in typescript pretty useless in my opition.
I would be glad to know your opinion on this matter :)
Also, there is a small code style adjustment if you don't mind. Switch branches for valid types can be merged:

switch (m.type) {
    case 'work':
    case 'exit': 
      return handlers[m.type](m);
    default: {
     const n: never = m;
     throw new Error(`This can never happen: ${n}`);
    }
  }
 

Thanks for the comment. TypeScript is not OCaml or ML derivative language so it doesn't have pattern matching but it has exhaustiveness checking so the compiler still helps with switch statements.

Re: combining the branches. The compiler isn't smart enough to verify the combined case so they have to be separate for exhaustiveness checking and type inference to work.

code of conduct - report abuse