Skip to content
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

feat: Update refined type for typescript with type guard validation #168

Merged
merged 2 commits into from
Feb 16, 2024

Conversation

ZzAve
Copy link
Collaborator

@ZzAve ZzAve commented Feb 16, 2024

Based on initial experience, the wrapped value for Typescript's refined type seems a bit bloated.

Old generated code for typescript:

export type UUID = {
   value: String
}
const validateUUID = (type: UUID) => (new = RegExp(
  "^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$").test(type.value);

New generated code for typescript:

export type UUID = string;
const regExp: RegExp = RegExp(
  "^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$"
);
export const validateUUID = (value: string): value is UUID =>
  regExp.test(value);

In an ideal world, the UUID would be more strongly typed string template literals, but this seems an open discussion within the typescript community. microsoft/TypeScript#41160

@jerrevanveluw jerrevanveluw merged commit 80a4ede into master Feb 16, 2024
8 checks passed
@jerrevanveluw jerrevanveluw deleted the better-refined-type-checking branch February 16, 2024 13:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants