-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeScriptOnly.ts
66 lines (52 loc) · 1.44 KB
/
TypeScriptOnly.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
import '@jsfe/shoelace';
import type { FromSchema, JSONSchema7 } from '@jsfe/shoelace';
// -----------------------------------------------------------------------------
const mySchema = {
type: 'object',
properties: {
foo: {
type: 'string',
},
bar: {
type: 'boolean',
},
},
} as const satisfies JSONSchema7;
type MyData = FromSchema<typeof mySchema>;
function assertValidData(data: unknown): data is MyData {
// Use your AJV or other schema checker here, if you need thorough validation
// ...
return true;
}
class TypeScriptOnly extends HTMLElement {
#form = this.querySelector('jsf-shoelace')!;
#debug = this.querySelector('pre')!;
protected _print(data: unknown) {
this.#debug.innerText = JSON.stringify({ data }, null, 2);
}
connectedCallback() {
this.#form.schema = mySchema;
this.#form.uiSchema = {
/* Type-casted as UiSchema */
bar: {
'ui:widget': 'switch',
},
};
this.#form.data = {
foo: 'hello',
} satisfies MyData;
this._print(this.#form.data);
this.#form.dataChangeCallback = (newData) => {
console.log({ 'Data from TypeScript': newData });
if (assertValidData(newData)) this._print(newData);
else console.error('Invalid data!');
};
this.#form.submitCallback = (newData, valid) => {
console.log({ 'Submitted from TypeScript!': newData, valid });
if (assertValidData(newData)) {
// Do stuff...
}
};
}
}
customElements.define('type-script-only', TypeScriptOnly);