-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtyped.go
More file actions
27 lines (25 loc) · 716 Bytes
/
typed.go
File metadata and controls
27 lines (25 loc) · 716 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package check
import "fmt"
// ParseTyped validates a value against a schema and returns a typed result.
// This avoids the need to type-assert the result of Parse.
//
// Usage:
//
// name, err := check.ParseTyped[string](z.String().Min(3), "Alice")
// age, err := check.ParseTyped[int](z.Int().Positive(), 25)
// users, err := check.ParseTyped[[]any](z.Array(z.String()), data)
func ParseTyped[T any](schema Schema, value any) (T, error) {
var zero T
result, err := schema.Parse(value)
if err != nil {
return zero, err
}
if result == nil {
return zero, nil
}
typed, ok := result.(T)
if !ok {
return zero, fmt.Errorf("type assertion failed: expected %T, got %T", zero, result)
}
return typed, nil
}