Skip to content

Commit ded20d2

Browse files
committed
make spec.assert also return value
1 parent 4a3297f commit ded20d2

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ spec.conform(user_spec, bob) -- returns nil
7777

7878
-- assert that the spec is valid otherwise throw an error
7979
spec.assert(spec.string, "Hello, World")
80+
81+
-- assert also returns the value if its valid so you can use this to check things passed into functions
82+
promote_user(spec.assert(user_spec, alice))
8083
```
8184

8285
## License

spec.lua

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,13 @@ function M.conform(spec, value)
159159
end
160160

161161
---Asserts that a spec is valid
162-
---@param spec any
163-
---@param value any
162+
---@generic T
163+
---@param spec fun(value: any): boolean
164+
---@param value T
165+
---@return T
164166
function M.assert(spec, value)
165167
assert(M.valid(spec, value))
168+
return value
166169
end
167170

168171
return M

spec_test.lua

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,5 +228,8 @@ describe("spec.lua", function()
228228
assert.has_error(function()
229229
spec.assert(spec.string, 1337)
230230
end)
231+
232+
local x = spec.assert(spec.number, 42)
233+
assert.equal(42, x)
231234
end)
232235
end)

0 commit comments

Comments
 (0)