Enum-specific interfaces enums could implement #39773
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Search Terms
Suggestion
Make interfaces work with enums.
Enum interface
An interface describing what an enum should look like.
Enum implements enum interface
Enum implements an
enum interface
by including in its values the fields described by the interface.This mechanism should also work for
const enums
. The same interface should be implementable by both aconst enum
and a regularenum
.An
enum interface
could require for the enum to have a specific value, although it is not necessary.An
enum interface
which has strict requirements for both the names and values would throw an error where either the name is not present in the enum implementing the interface or if the name is present but the value is not the same as the one defined in the interface.Use Cases
Let say I'm creating an API. Each response I encode as a
const enum
result. Each of the response has some of the same results, (same possible errors) for example:Both a
/post
(creating a post) request and a/post
(deleting a post) requestmay trigger the same errors regarding lack of authentication. Here I demonstrate two
const enum
s describing the possible results of the two endpoints.Now, before the API handler in a perfect world one could create a method of signature:
Which would be fine, but
makeError
needs to be called from inside therequireAuthentication
with a known error like,NO_AUTHENTICATION
. So what is needed is:requireAuthentication
middleware may trigger into the particular result of the particular endpoint (in this case either aCreatePost
orDeletePost
enum),requireAuthentication
.Now with a few endpoints this is fine, but in production one can have a large number of endpoints for which a status map object has to be constructed manually for each endpoint:
Now this is a simplified example, but in real life one could have lots of endpoints and lots of possible ways for things to fail.
Examples
As for the solution, the perfect thing for this use-case would be to make an enum interface:
Which then could be implemented on all endpoints' result enums:
Which would then stop us from having to create an object for each endpoint with the
AuthenticationErrorMap
type. Instead something like this could be written:Playground.
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: