Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
kterui9019 opened this issue Nov 3, 2023 · 2 comments
Closed

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

kterui9019 opened this issue Nov 3, 2023 · 2 comments
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.

Comments

@kterui9019
Copy link

kterui9019 commented Nov 3, 2023

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);
}
@kterui9019 kterui9019 added flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features. labels Nov 3, 2023
@kterui9019
Copy link
Author

kterui9019 commented Nov 3, 2023

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.

@braaar
Copy link
Member

braaar commented Jan 11, 2024

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.

@typestack typestack locked and limited conversation to collaborators Jan 11, 2024
@braaar braaar converted this issue into discussion #2365 Jan 11, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.
Development

No branches or pull requests

2 participants