Skip to content

feature: Implement type guard in the isEnum() function #2300

Closed

Description

@kterui9019

Description

The isEnum() function does not implement type guard.
This is inconvenient when writing code like the following

const somefunction(value: string): USERTYPE => {
  if (!isEnum(value, USERTYPE)) throw new Error("not match enum");
  return value; // Type 'string' is not assignable to type 'USERTYPE'. ts(2322)
}

Proposed solution

A type guard should be implemented in the isEnum() function.
I am now wrapping the isEnum() function in the type guard function myself.

function validateEnumValue<T>(value: any, enumeration: T): value is T[keyof T] {
  return isEnum(value, enumulation);
}

Activity

  1. kterui9019 commented on Nov 3, 2023

    @kterui9019
    Author

    Specifically, I believe this can be accomplished by modifying the code as follows.

    export function isEnum<T extends Record<string | number, unknown>>(value: unknown, entity: T): value is T[keyof T]  {
      const enumValues = Object.values(entity);
      return enumValues.includes(value);
    }

    I can send you a pull request if you like.

  2. braaar commented on Jan 11, 2024

    @braaar
    Member

    I'm moving this to the discussion tab, as we are trying to keep the issue count low. Please see this issue for an explanation.

  3. locked and limited conversation to collaborators on Jan 11, 2024
  4. converted this issue into a discussion #2365 on Jan 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions