Skip to content

Commit 2a141b3

Browse files
authored
Merge pull request #73 from remnantkevin/fix-json-type-inference
Fix typing of `json` runtype output
2 parents 14fe0ac + 65d2354 commit 2a141b3

File tree

3 files changed

+44
-2
lines changed

3 files changed

+44
-2
lines changed

src/json.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ export const jsonRuntype = internalRuntype<unknown>((v, failOrThrow) => {
2424
/**
2525
* A String that is valid json
2626
*/
27-
export function json<T>(rt: Runtype<any>): Runtype<T> {
28-
return internalRuntype<T>((v, failOrThrow) => {
27+
export function json<T>(rt: Runtype<T>): Runtype<T> {
28+
return internalRuntype<any>((v, failOrThrow) => {
2929
const n = (jsonRuntype as InternalRuntype)(v, failOrThrow)
3030

3131
if (isFail(n)) {

test-d/json.test-d.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { expectType } from 'tsd'
2+
import * as st from '../src'
3+
4+
const data: unknown = null
5+
6+
// basic
7+
{
8+
// number
9+
const jsonNumberRt = st.json(st.number())
10+
11+
expectType<number>(jsonNumberRt(data))
12+
13+
// string
14+
const jsonStringRt = st.json(st.string())
15+
16+
expectType<string>(jsonStringRt(data))
17+
18+
// array
19+
const jsonArrayRt = st.json(st.array(st.number()))
20+
21+
expectType<number[]>(jsonArrayRt(data))
22+
23+
// object
24+
const jsonObjectRt = st.json(st.record({ a: st.string() }))
25+
26+
expectType<{ a: string }>(jsonObjectRt(data))
27+
}

test-d/record.test-d.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,18 @@ const data: unknown = null
3535

3636
expectType<{ a: { b: { c: string } } }>(rt(data))
3737
}
38+
39+
// record with json
40+
{
41+
const rt = st.record({
42+
a: st.string(),
43+
b: st.json(
44+
st.record({
45+
c: st.string(),
46+
}),
47+
),
48+
d: st.string(),
49+
})
50+
51+
expectType<{ a: string; b: { c: string }; d: string }>(rt(data))
52+
}

0 commit comments

Comments
 (0)