stepchowfun / typical

Data interchange with algebraic data types.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Documentation request: schema file for "shape" typescript example

stmarier opened this issue · comments

Description
It would be nice to see an example types.t file for the exhaustive pattern matching typescript example in the documentation, if you have the time for it. I'm sure for many readers it is obvious from the documentation written so far how one would create a schema that would generate this code, but not for me, and I think the extra example case would help my understanding of the project a lot.

Thanks for considering it!

Hi @stmarier, thank you for opening this issue! I can see how that part of the documentation can cause confusion.

Here's an example schema for that example:

struct Square {
  sideLength: F64 = 0
}

struct Rectangle {
  width: F64 = 0
  height: F64 = 1
}

struct Circle {
  radius: F64 = 0
}

choice Shape {
  square: Square = 0
  rectangle: Rectangle = 1
  circle: Circle = 2
}

After you've generated the code for that schema, you might use it in a TypeScript file as follows:

import { Types, unreachable } from '../generated/types';

type ShapeIn = Types.ShapeIn;

function area(shape: ShapeIn): number {
  switch (shape.$field) {
    case 'square':
      return shape.square.sideLength * shape.square.sideLength;
    case 'rectangle':
      return shape.rectangle.width * shape.rectangle.height;
    case 'circle':
      return Math.PI * shape.circle.radius * shape.circle.radius;
    default:
      return unreachable(shape);
  }
}

I hope that is helpful! I'll leave this issue open until I have a chance to clarify the documentation.