How do I validate an Enum with a Regex? #1363
-
|
Hello there! I'm an aspiring game developer that's been using Pkl for a couple days now, and I'm really enjoying how it works so far! It feels a lot more versatile compared to cue, and seems very capable for what I'm using it for. Thus, I hope I'm not asking an unusual question, but I want to know if it's possible to validate an Enum's values with some Regex, and if it is possible, how to do it. To give an example of what I'm talking about, let's say I have a file like this: What I want to do is to use To give a bit of context, I'm using the StatusEnum's as a sort of Identification system for figuring out what statuses to apply onto skills (which are also formed in Pkl), since that seems like the best way of doing it in my mind. Thank you for your consideration! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
Hi there! Glad to hear you're enjoying using Pkl 😁 If I'm interpreting your question correctly, you want to add some kind of assertion that the string literal types that are members of the import "pkl:reflect"
status: StatusEnum = "STATUS_BLEED"
typealias _StatusEnum = "STATUS_BLEED" | "STATUS_COLD" | "STATUS_RAGE" | "STATUS_Frozen"
hidden const statusRegex = Regex(#"^STATUS_([A-Z0-9_]+)$"#)
typealias StatusEnum =
_StatusEnum(
(reflect.TypeAlias(_StatusEnum).referent as reflect.UnionType).members.every((it) ->
let (enumCase = (it as reflect.StringLiteralType).value)
enumCase.matches(statusRegex)
|| throw(
"StatusEnum case \(enumCase) does not match required pattern `\(statusRegex.pattern))`"
)
),
)Attempting to evaluate this results in a helpful error: As you can see, this requires a little bit of indirection in the form of a second |
Beta Was this translation helpful? Give feedback.
Hi there! Glad to hear you're enjoying using Pkl 😁
If I'm interpreting your question correctly, you want to add some kind of assertion that the string literal types that are members of the
StatusEnumunion match a certain pattern. There isn't a super straightforward way to do this, but it is possible with Pkl's reflection library. Here's how: