Skip to content

Add support for const keyword #1834

Open
@robertadkins

Description

@robertadkins

I have a usecase where it would be helpful to support constant values via the const keyword.

Say we have an api spec containing some models like:

{
  "components": {
    "schemas": {
      "Animal": {
        "anyOf": [
          {
            "$ref": "#/components/schemas/Dog"
          },
          {
            "$ref": "#/components/schemas/Cat"
          }
        ]
      },
      "Dog": {
        "type": "object",
        "properties": {
          "type": {
            "const": "Dog"
          },
          "isPuppy": {
            "type": "boolean",
          }
        }
      },
      "Cat": {
        "properties": {
          "type": {
            "const": "Cat"
          },
          "isKitten": {
            "type": "boolean",
          }
        }
      }
    }
  }
}

In typescript, this should map to something like:

type Animal = Dog | Cat;
type Dog = {
  type: "Dog";
  isPuppy: boolean;
};
type Cat = {
  type: "Cat";
  isKitten: boolean;
};

This way, we can narrow the type in a useful way:

function isBaby(animal: Animal): boolean {
  switch(animal.type) {
    case "Dog":
      return animal.isPuppy;
    case "Cat":
      return animal.isKitten;
  }
}

However, openapi-typescript-codegen maps const values to any types, so the type information is lost.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions