Skip to content

How do you define generic-like schemas? #230

Answered by gregsdennis
GabenGar asked this question in Q&A
Discussion options

You must be logged in to vote

I've actually been considering doing a blog post on this.

This is a perfect application for 2020-12's $dynamicAnchor and $dynamicRef.

Let's start with the generic definition.

interface IAPIResponseSuccess<DataType> {
  ok: true
  data: DataType
}

For this, we want to create the wrapper without knowing what DataType is.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://my.server/IAPIResponseSuccess",
  "type": "object",
  "$defs": {
    "DataType": {
        "$dynamicAnchor": "DataType",
        "not": true
    }
  },
  "properties": {
    "ok": { "const": true },
    "data": { "$dynamicRef": "#DataType" }
  },
  "required": [ "ok", "data" ]
}

So this schema …

Replies: 2 comments 14 replies

Comment options

You must be logged in to vote
1 reply
@GabenGar
Comment options

Comment options

You must be logged in to vote
13 replies
@jdesrosiers
Comment options

@GabenGar
Comment options

@handrews
Comment options

@GabenGar
Comment options

@handrews
Comment options

Answer selected by handrews
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants