Skip to content

Enable constants as computed values for string enums #40793

Closed
@kataik

Description

@kataik

Search Terms

'TS18033', 'typescript define enum with constant string value', 'string enum computed constant'

Suggestion

Please consider enabling to use constant variables as values for string enums. The following code snippet fails compilation with TS18033 ('Only numeric enums can have computed members, but this expression has type 'string'. If you do not need exhaustiveness checks, consider using an object literal instead.')

const VALUE: string = 'ENUM_VALUE';

enum MyEnum {
  KEY = VALUE, // <-- Fails with TS18033
}

console.log(MyEnum.KEY);

, whereas the following passes:

enum Values {
  VALUE = 'ENUM_VALUE',
}

enum MyEnum {
  KEY = Values.VALUE,
}

console.info(MyEnum.KEY);

Use Cases

Use string interpolation (templated strings) when defining the value of a string enum to be able to reuse pre-defined constants as part of the value. (E.g. namespace prefixes, extension postfixes)

Examples

const NAMESPACE: string = 'com.mycompany.myservice';

enum Errors {
  INVALID_INPUT_ERROR = `${NAMESPACE}.errors#InvalidInput`,
}

Checklist

My suggestion meets these guidelines:

  • [ X ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [ X ] This wouldn't change the runtime behavior of existing JavaScript code
  • [ X ] This could be implemented without emitting different JS based on the types of the expressions
  • [ X ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [ X ] This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureFix AvailableA PR has been opened for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions