typespec icon indicating copy to clipboard operation
typespec copied to clipboard

How to create an integer enum

Open mahomedalid opened this issue 2 years ago • 10 comments

The following enum:

import "@typespec/rest";
import "@typespec/openapi3";

...

enum DayOfWeek
{
    Monday: 0,
    Tuesday: 1,
    Wednesday: 2,
    Thrusday: 3,
    Friday: 4,
    Saturday: 5,
    Sunday: 6
}

Generates a number enum. Is there any decorator (or way) to force it to an int32 enum? I did try to find something in the documentation without luck.

mahomedalid avatar Mar 20 '23 17:03 mahomedalid

What is an int32 enum? OpenAPI doesn't have that concept I believe. Are you wanting to see a particular output in some other emitter?

bterlson avatar Mar 20 '23 18:03 bterlson

@bterlson sorry, it was integer.

When generating the spec from the base asp.net sample todo app it generates this:

"DayOfWeek": {
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6
        ],
        "type": "integer",
        "format": "int32"
      },

Looking into the spec (https://spec.openapis.org/oas/v3.0.3#schema-object) seems type and format are taken directly from JSONSchema. Looking into the code, seems member can either be a string or a number correct? https://github.com/microsoft/typespec/blob/c2e12473283cdb6e409caf69d38fad70e3beed27/packages/compiler/core/types.ts#L286

mahomedalid avatar Mar 21 '23 00:03 mahomedalid

I think at the end it does not matter, I suppose, since there is a set of predefined values, it cannot be outside any of those values independently if are integer or number.

mahomedalid avatar Mar 21 '23 00:03 mahomedalid

JSON Schema doesn't define that format afaict, so I'm actually a little confused why we generate it in the first place. @mikekistler any thoughts? Is this something we should even be including in the output?

bterlson avatar Mar 21 '23 01:03 bterlson

The format is from here: https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#section-7.3

Use of format in OpenAPI2 predates any mention in Json Schema, though.

markcowl avatar Mar 21 '23 01:03 markcowl

It doesn't define the int32 format specifically though. While the spec allows for arbitrary values, it seems weird that we would include a format that most (all?) implementations wouldn't support. If the range of values is important, we could emit minimum and maximum which would be broadly supported...

bterlson avatar Mar 21 '23 01:03 bterlson

OpenAPI v2 does define the int32 format explicitly.

image

mikekistler avatar Mar 21 '23 02:03 mikekistler

3.0.3 also https://spec.openapis.org/oas/v3.0.3#dataTypeFormat

image

mahomedalid avatar Mar 21 '23 02:03 mahomedalid

@markcowl correlate with bitfield support

markcowl avatar Mar 21 '23 16:03 markcowl

`Related to: https://github.com/microsoft/typespec/issues/1237

markcowl avatar Mar 21 '23 16:03 markcowl