microsoft / microsoft/typespec

[Bug]: Enum values should be usable in string/numeric contexts

Open
#4,302 6 comments 4 reactions 0 assignees View on GitHub
compiler:core design:needed triaged:core
Dominant language
Java
Stars
5.9k
Forks
394
Avg merge
1d 23h
Merged PRs (30d)
104

Description

### Describe the bug

I expect that enum values should be usable in numeric/string value contexts, based on:
- the documentation at https://typespec.io/docs/language-basics/values#enum-member--union-variant-references
- the discussion at https://github.com/microsoft/typespec/discussions/4247

However, such uses result in TypeSpec errors (confirmed in 0.59.x TypeSpec playground):

```typespec
enum Constants {
MY_CONSTANT: 10,
MY_STRING_CONSTANT: "hello",
}

model Test {
int_field: safeint = Constants.MY_CONSTANT; // "Type 'Constants.MY_CONSTANT' is not assignable to type 'safeint'"

@minValue(Constants.MY_CONSTANT) // Argument of type 'Constants.MY_CONSTANT' is not assignable to parameter of type 'valueof numeric'
min_field: safeint;

str_field: string = Constants.MY_STRING_CONSTANT; // Type 'Constants.MY_STRING_CONSTANT' is not assignable to type 'string'

@doc(Constants.MY_STRING_CONSTANT) // Argument of type 'Constants.MY_STRING_CONSTANT' is not assignable to parameter of type 'valueof string'
doc_field: string;
}
```

Narrower versions of this issue:
- https://github.com/microsoft/typespec/issues/1720
- https://github.com/microsoft/typespec/issues/2227

### Reproduction

https://typespec.io/playground?c=ZW51bSBDb25zdGFudHMgewogIE1ZX0NPTlNUQU5UOiAxMCzGE1NUUklOR8saImhlbGxvIiwKfQoKbW9kZWwgVGVzdMVCaW50X2ZpZWxkOiBzYWZlaW50ID3KZS7LYTsgLy8gIlR5cGUgJ9UhJyBpcyBub3QgYXNzaWduYWJsZSB0byB0xTLHXSciCgogIEBtaW5WYWx1ZSjVSSnEakFyZ3VtZW50IG9mx0Pfdc11cGFyYW1ldGVyyj92xHFvZiBudW1lcmljJwogIG1pbu8A%2FTvkAJ9zdHLJF3RyaW5n8AET7wFh5QEa8wEZzyf%2BASDFaSfEf0Bkb2PuARnPSf8BIN98%2FwEn6AEn6ACRICBkb2PuAQ87Cn0K&e=%40typespec%2Fopenapi3&options=%7B%7D

### Checklist

- [X] Follow our [Code of Conduct](https://github.com/microsoft/typespec/blob/main/CODE_OF_CONDUCT.md)
- [X] Check that there isn't already an issue that request the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A open a [GitHub Discussion](https://github.com/Microsoft/typespec/discussions).
- [X] The provided reproduction is a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of the bug.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.