Skip to content

Commit d8d0ea7

Browse files
committed
Add JSONSchema $defs docs
1 parent 663bd5e commit d8d0ea7

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

docs/src/content/docs/advanced.md

+69
Original file line numberDiff line numberDiff line change
@@ -351,3 +351,72 @@ prefixItems:
351351
352352
</tbody>
353353
</table>
354+
355+
### Use `$defs` only in objects
356+
357+
<a href="https://json-schema.org/understanding-json-schema/structuring.html#defs" target="_blank" rel="noopener noreferrer">JSONSchema $defs</a> can be used to provide sub-schema definitions anywhere. However, these won’t always convert cleanly to TypeScript. For example, this works:
358+
359+
```yaml
360+
components:
361+
schemas:
362+
DefType:
363+
type: object # ✅ `type: "object"` is OK to define $defs on
364+
$defs:
365+
myDefType:
366+
type: string
367+
MyType:
368+
type: object
369+
properties:
370+
myType:
371+
$ref: "#/components/schemas/DefType/$defs/myDefType"
372+
```
373+
374+
This will transform into the following TypeScript:
375+
376+
```ts
377+
export interface components {
378+
schemas: {
379+
DefType: {
380+
$defs: {
381+
myDefType: string;
382+
};
383+
};
384+
MyType: {
385+
myType?: components["schemas"]["DefType"]["$defs"]["myDefType"]; // ✅ Works
386+
};
387+
};
388+
}
389+
```
390+
391+
However, this won’t:
392+
393+
#### ❌ Doesn’t work
394+
395+
```yaml
396+
components:
397+
schemas:
398+
DefType:
399+
type: string # ❌ this wont keep its $defs
400+
$defs:
401+
myDefType:
402+
type: string
403+
MyType:
404+
properties:
405+
myType:
406+
$ref: "#/components/schemas/DefType/$defs/myDefType"
407+
```
408+
409+
Because it will transform into:
410+
411+
```ts
412+
export interface components {
413+
schemas: {
414+
DefType: string;
415+
MyType: {
416+
myType?: components["schemas"]["DefType"]["$defs"]["myDefType"]; // ❌ Property '$defs' does not exist on type 'String'.
417+
};
418+
};
419+
}
420+
```
421+
422+
So be wary about where you define `$defs` as they may go missing in your final generated types. When in doubt, you can always define `$defs` at the root schema level.

0 commit comments

Comments
 (0)