npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-union-parser

v0.1.5

Published

A parser generator for discriminated unions.

Downloads

2

Readme

ts-union-parser

A CLI tool for generating parsers from discriminated union TypeScript types.

Version Downloads/week

Use case

Suppose you have the following types defining the shape of data you'll be sending over a WebSocket connection:

type MessageRequest = {
  type: 'request';
  item: 'state' | 'user-count';
}

type MessageState = {
  type: 'state';
  state: State;
}

type MessageUserCount = {
  type: 'user-count';
  count: number;
}

type MessageError = {
  type: 'error';
  message?: string;
}

type State = {
  connections: number;
  status: 'ok' | 'err';
}

/**
 * This is a "discriminated union". TypeScript can narrow the type of a `Message`
 * using the `type` field, which is unique for each of the four types of the union. 
 */
type Message = MessageRequest | MessageState | MessageUserCount | MessageError;

When a WebSocket message is received, we often want to parse it and validate that it is the correct shape before attempting to perform any logic using the (potentially ill-formed) data. This script will generate a parser function that does this parsing and validation step. The output given the types above is:

export function parser(data: string): Message {
  const _data = JSON.parse(data);
  if (typeof _data !== 'object') {
    throw new Error('Parsed data is not an object');
  }
  if (!_data.hasOwnProperty('type')) {
    throw new Error('Parsed data does not have "type" field.');
  }
  switch (_data['type']) {
    case 'request':
      if (isMessageRequest(_data)) return _data as MessageRequest;
    case 'state':
      if (isMessageState(_data)) return _data as MessageState;
    case 'user-count':
      if (isMessageUserCount(_data)) return _data as MessageUserCount;
    case 'error':
      if (isMessageError(_data)) return _data as MessageError;
    default:
      throw new Error(
        'Parsed data does not contain valid discriminator value.'
      );
  }
}
function isMessageRequest(data: any): data is MessageRequest {
  return (
    typeof data === 'object' &&
    data['type'] === 'request' &&
    (data['item'] === 'state' || data['item'] === 'user-count')
  );
}
function isMessageState(data: any): data is MessageState {
  return (
    typeof data === 'object' &&
    data['type'] === 'state' &&
    isState(data['state'])
  );
}
function isState(data: any): data is State {
  return (
    typeof data === 'object' &&
    typeof data['connections'] === 'number' &&
    (data['status'] === 'ok' || data['status'] === 'err')
  );
}
function isMessageUserCount(data: any): data is MessageUserCount {
  return (
    typeof data === 'object' &&
    data['type'] === 'user-count' &&
    typeof data['count'] === 'number'
  );
}
function isMessageError(data: any): data is MessageError {
  return (
    typeof data === 'object' &&
    data['type'] === 'error' &&
    (data.hasOwnProperty('message')
      ? typeof data['message'] === 'string'
      : true)
  );
}