Enumerations of product type instances or checks on instances #2078
|
Hi, we are implementing a configuration for the definition of our domain and we would like to define a set of instances for a given product type that define our ADT/enum, so I tried this but it is not working: schema _InternalContextType:
id: int
name: str
description?: str
A = _InternalContextType { id = 1 name = "A" }
B = _InternalContextType { id = 2 name = "B" }
C = _InternalContextType { id = 3 name = "C" }
type ContextType = A | B | CSo when using the What alternatives do we have to implement the safety guards we need to apply? Thanks! |
Replies: 1 comment
|
A 1. Keep the instances, enforce membership with a schema ContextType:
id: int
name: str
description?: str
A = ContextType { id = 1, name = "A" }
B = ContextType { id = 2, name = "B" }
C = ContextType { id = 3, name = "C" }
_allowed = [A, B, C]
schema Service:
name: str
context: ContextType
check:
context in _allowed, "context must be one of A, B, C, got ${context.name}"
ok = Service { name = "svc", context = B }
bad = Service { name = "x", context = ContextType { id = 4, name = "D" } }
# -> Check failed on the condition: context must be one of A, B, C, got D
2. Make the enum a literal union of keys and look the instance up CONTEXTS: {str:ContextType} = {
A = { id = 1, name = "A" }
B = { id = 2, name = "B" }
C = { id = 3, name = "C" }
}
type ContextName = "A" | "B" | "C"
schema Service:
name: str
contextName: ContextName
context: ContextType = CONTEXTS[contextName]
ok = Service { name = "svc", contextName = "B" } # context is filled in from CONTEXTS
bad = Service { name = "x", contextName = "Z" }
# -> TypeError: expected str(A) | str(B) | str(C), got str(Z)Option 2 is caught at compile time by the type checker, and users can only pick a name, not hand-build an instance. Option 1 is a runtime check, but it lets you pass the instances around directly. If this solves it, please mark it as the answer so others with the same problem can find it. |
A
typealias can only be a union of types and literal values ("a" | "b",1 | 2, schema names).A,BandCare variables holding instances, so the type checker doesn't resolve them there, hencename 'A' is not defined. Two patterns that give you the guard (both tested with KCL 0.13.3):1. Keep the instances, enforce membership with a
checkblock