Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tagged unions #81

Merged
merged 1 commit into from
Sep 27, 2016
Merged

Tagged unions #81

merged 1 commit into from
Sep 27, 2016

Conversation

vojtechhabarta
Copy link
Owner

This feature takes advantage of TypeScript 2.0 tagged union types but generated declarations are also valid in TypeScript 1.8.

This PR implements tagged (or discriminated) unions for Jackson 2 polymophic types. Jackson library allows to define additional property which marks particular subclasses so that when reading JSON data it is possible to distinguish several subclasses.

In following example Jackson uses kind property with defined value for each subclass

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind")
@JsonSubTypes({
    @JsonSubTypes.Type(Square.class),
    @JsonSubTypes.Type(Rectangle.class),
})
public abstract class Shape {
}

@JsonTypeName("square")
public class Square extends Shape {
    public double size;
}

@JsonTypeName("rectangle")
public class Rectangle extends Shape {
    public double width;
    public double height;
}

Example JSON array of shapes generated using such classes

[
    {
        "kind": "square",
        "size": 4.0
    },
    {
        "kind": "rectangle",
        "width": 5.0,
        "height": 3.0
    }
]

To simplify processing of such data typescript-generator generates ShapeUnion (tagged union type) with kind discriminant property

type ShapeUnion = Square | Rectangle;

interface Square extends Shape {
    kind: "square";
    size: number;
}

interface Rectangle extends Shape {
    kind: "rectangle";
    width: number;
    height: number;
}

interface Shape {
    kind: "square" | "rectangle";
}

So it is possible to test if shape is for example square

let shape: ShapeUnion;

if (shape.kind === "square") {
    // here TypeScript 2.0 knows that shape is Square
    console.log("Square size: " + shape.size);

    // this cast is needed in TypeScript 1.8
    let square = <Square>shape;
    console.log("Square size: " + square.size);
}

This feature can be suppressed in typescript-generator using disableTaggedUnions parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant