Closed
Description
Search Terms
enums
Suggestion
Because enums do not work as expected...
const enum MyEnum {
Zero,
One
}
const foo: MyEnum.Zero = 0 // Ok as expected (since MyEnum.Zero is zero)
const bar: MyEnum.Zero = 1 // OK, but expected Error!
...people start using this workaround (aka "namespace-as-enum"):
namespace MyEnum {
export const Zero = 0;
export type Zero = typeof Zero;
export const One = 1;
export type One = typeof One;
}
type MyEnum = typeof MyEnum[keyof typeof MyEnum];
const foo: MyEnum.Zero = 0 // okay as expected
const bar: MyEnum.Zero = 1 // error as expected
Maybe there should be a less verbose way to do this common stuff?
For example it could be something like enum MyEnum {type Zero, type One}
Use Cases
I use number values (i.e. enums) extensively instead of string values for performance reasons (a lot of JSON.stringify/parse).
Examples
// Syntax A...
const enum MyEnum {
type Zero,
type One
}
// ...or syntax B (C++ style)
const enum class MyEnum {
Zero,
One
}
const foo: MyEnum.Zero = 0 // Ok
const bar: MyEnum.Zero = 1 // Error!
C++ had the same problem and they fixed it
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.