deno.land / x / xstate@xstate@4.33.6 / test / schema.test.ts

schema.test.ts
نووسراو ببینە
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { createMachine, createSchema } from '../src';
namespace JSONSchema { export interface String { type: 'string'; } export interface Number { type: 'number'; } export interface Object<TK extends string> { type: 'object'; properties: { [key in TK]: JSONSchema.Thing; }; } export type Thing = | JSONSchema.String | JSONSchema.Number | JSONSchema.Object<string>; export type TypeFrom<T extends JSONSchema.Thing> = T extends JSONSchema.String ? string : T extends JSONSchema.Number ? number : T extends JSONSchema.Object<infer Keys> ? { [Key in Keys]: TypeFrom<T['properties'][Key]>; } : unknown;}
function fromJSONSchema<T extends JSONSchema.Thing>( schema: T): JSONSchema.TypeFrom<T> { return schema as any;}
describe('schema', () => { it('should infer types from provided schema', () => { const noop = (_: any) => void 0;
const m = createMachine({ schema: { context: fromJSONSchema({ type: 'object', properties: { foo: { type: 'string' }, bar: { type: 'number' }, baz: { type: 'object', properties: { one: { type: 'string' } } } } }), events: createSchema<{ type: 'FOO' } | { type: 'BAR' }>() }, context: { foo: '', bar: 0, baz: { one: '' } }, initial: 'active', states: { active: { entry: ['asdf'] } } });
noop(m.context.foo); noop(m.context.baz.one); m.transition('active', 'BAR');
// @ts-expect-error noop(m.context.something);
// @ts-expect-error m.transition('active', 'INVALID'); });
it('schema should be present in the machine definition', () => { const schema = { context: fromJSONSchema({ type: 'object', properties: { foo: { type: 'string' } } }) };
const m = createMachine({ schema, context: { foo: '' }, initial: 'active', states: { active: {} } });
expect(m.schema).toEqual(schema); });});
xstate

Version Info

Tagged at
2 years ago