Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make InputFieldJSONSchema.properties work with specialized types #1894

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jonathaningram
Copy link

InputFieldJSONSchema is a base type that can be specialized. E.g. InputField specializes it.

However, in the base type, properties is defined in terms of a specialized type.

This makes it hard to correctly type properties. For example, specializing InputField with, say, EditableInputField means that properties would be defined in terms of InputField, not EditableInputField.

Instead, we can use TypeScript's polymorphic this type to define properties.

Testing

Let's define some sample input field arrays to demonstrate:

const xs: InputFieldJSONSchema[] = [
  {
    label: 'l',
    type: 'string',
    description: 'd',
    properties: {
      a: {
        label: 'a',
      }
    },
  }
];

const ys: InputField[] = [
  {
    label: 'l',
    type: 'string',
    description: 'd',
    properties: {
      a: {
        label: 'a',
      }
    },
  }
];

Compare how TS sees these two arrays of input fields.

Old code

TS only understands that properties is a map of InputField, which makes sense because it's hard coded.

For xs:

image

And ys:

image

New code

TS uses the specialized type for the properties map.

For xs:

image

For ys:

image

Add a new specialized type EditableInputField:

interface EditableInputField extends InputField {
  value: FieldValue;
}

And a test array for this:

const zs: EditableInputField[] = [
  {
    label: 'l',
    type: 'string',
    description: 'd',
    value: {
      '@path': '$.l'
    },
    properties: {
      a: {
        label: 'a',
      }
    },
  }
];

And we can see that TS also correctly understands that properties is now this specialized type:

image

`InputFieldJSONSchema` is a base type that can be specialized. E.g.
`InputField` specializes it.

However, in the base type, `properties` is defined in terms of a
specialized type.

This makes it hard to correctly type `properties`. For example,
specializing `InputField` with, say, `EditableInputField` means that
`properties` would be defined in terms of `InputField`, not
`EditableInputField`.

Instead, we can use TypeScript's [polymorphic this type] to define
`properties`.

[polymorphic this type]: https://stackoverflow.com/a/67307495
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants