Skip to content

Latest commit

 

History

History
54 lines (45 loc) · 1.47 KB

enum-vs-union-types.md

File metadata and controls

54 lines (45 loc) · 1.47 KB

Enums vs. Union types

Flag: --useUnionTypes

The OpenAPI spec allows you to define enums inside the data model. By default, we convert these enums definitions to TypeScript enums. However, these enums are merged inside the namespace of the model, this is unsupported by Babel, see docs. Because we also want to support projects that use Babel @babel/plugin-transform-typescript, we offer the flag --useUnionTypes to generate union types instead of the traditional enums. The difference can be seen below:

Enums:

// Model
export type Order = {
    id?: number;
    quantity?: number;
    status?: Order.status;
};

export namespace Order {
    export enum status {
        PLACED = 'placed',
        APPROVED = 'approved',
        DELIVERED = 'delivered',
    }
}

// Usage
const order: Order = {
    id: 1,
    quantity: 40,
    status: Order.status.PLACED,
};

Union Types:

// Model
export type Order = {
    id?: number;
    quantity?: number;
    status?: 'placed' | 'approved' | 'delivered';
};

// Usage
const order: Order = {
    id: 1,
    quantity: 40,
    status: 'placed',
};