cds-typer icon indicating copy to clipboard operation
cds-typer copied to clipboard

[BUG] `Integer enum`s that don't have explicit values set produce broken types

Open daogrady opened this issue 1 year ago • 2 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Nature of Your Project

JavaScript, TypeScript

Current Behavior

When defining an integer enum without explicitly assigning values to the keys, the generated types will contain syntax errors (see repro for a sample model).

These enums can be compiled without issue, although the output looks a bit unexpected:

$ cds repl
> await cds.load('foo.cds')
{
  definitions: {
    Foo: {
      kind: 'type',
      type: 'cds.Integer',
      enum: { a: {}, b: {}, c: {} }
    }
  },
  meta: { creator: 'CDS Compiler v4.5.1', flavor: 'inferred' },
  '$version': '2.0'
}

Expected Behavior

~~Expected output is not clear either. I would have expected to have the keys enumerated in order, starting from 0 (or 1?). The type should be set accordingly.~~ Log a fatal error prompting the user to explicitly define values. See comment below. Type could be just number iff we want to make sure the run produces syntactically correct types even in this case.

Steps To Reproduce

  1. create a file:
// foo.cds
type Foo: Integer enum { a; b; c; }
  1. run:
cds-typer foo.cds
  1. check the generated index.ts file and find:
export const Foo = {
  a: undefined,
  b: undefined,
  c: undefined,
} as const;
export type Foo =   // <- syntax error

Environment

- **OS**: Mac
- **Node**: irrelevant
- **npm**: irrelevant
- **cds-typer**: 0.16
- **cds**: irrelevant

|  | https://github.com/<your/repo> |
|:---------------------- | ----------- |
| Node.js                | v19.9.0     |
| @sap/cds               | 7.6.0       |
| @sap/cds-compiler      | 4.5.1       |
| @sap/cds-dk            | -- missing  |
| @sap/cds-dk (global)   | 7.5.1       |
| @sap/eslint-plugin-cds | 2.6.5       |
| @sap/cds-mtxs          | 1.14.0      |
| @cap-js/cds-types      | -- missing  |

Repository Containing a Minimal Reproducible Example

No response

Anything else?

This is probably a rather easily fixable issue by iterating over the entries of integer enums and coalescing the values with their respective index.

https://github.com/cap-js/cds-typer/blob/main/lib/components/enum.js

daogrady avatar Feb 06 '24 09:02 daogrady