Discriminated Unions

The SDKs natively support discriminated unions for both OpenAPI and Fern APIs.

Discriminated unions are defined with the union key. For example, a simple Shape type that can either be a Triangle or a Square can be defined as follows:

fern/definition/shape.yml
1types:
2 Shape:
3 union:
4 triangle: Triangle
5 square: Square
6
7Triangle:
8 properties:
9 a: double
10 b: double
11 c: double
12
13Square:
14 properties:
15 side: double

With this, the JSON representation for a Shape looks like the following:

triangle.json
1{
2 "type": "triangle",
3 "a": 3,
4 "b": 4,
5 "c": 5
6}

or

square.json
1{
2 "type": "square",
3 "side": 5
4}

Discriminated unions are defined with the oneOf and anyOf keys. For example, consider the following Shape definition:

openapi.yml
1components:
2 schemas:
3 Shape:
4 oneOf:
5 - $ref: "#/components/schemas/Triangle"
6 - $ref: "#/components/schemas/Square"
7 Triangle:
8 type: object
9 properties:
10 type:
11 type: string
12 enum:
13 - triangle
14 a:
15 type: number
16 b:
17 type: number
18 c:
19 type: number
20 required:
21 - type
22 - a
23 - b
24 - c
25 Square:
26 type: object
27 properties:
28 type:
29 type: string
30 enum:
31 - square
32 side:
33 type: number
34 required:
35 - type
36 - side

With this, the JSON representation for a Shape looks like the following:

triangle.json
1{
2 "type": "triangle",
3 "a": 3,
4 "b": 4,
5 "c": 5
6}

or

square.json
1{
2 "type": "square",
3 "side": 5
4}
1export type Shape = Triangle | Square;
2
3export interface Triangle {
4 type: "triangle";
5 a: number;
6 b: number;
7 c: number;
8}
9
10export interface Square {
11 type: "square";
12 side: number;
13}

Callers can create a Shape object by simply constructing the appropriate type. For example, creating a Triangle shape looks like the following:

1const shape: Shape = {
2 type: "triangle",
3 a: 3,
4 b: 4,
5 c: 5,
6};

Consumers can easily write branching logic by checking the discriminant.

1import { Shape } from "sdk";
2
3export function computeArea(shape: Shape): number {
4 if (shape.type === "triangle") {
5 // compute triangle area
6 } else if (shape.type === "square") {
7 // compute square area
8 }
9}
Built with