json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

Support propertyNames with enum

Open Remirror-zz opened this issue 5 years ago • 1 comments

propertyNames is included in the "not expressible in TS" list, but at least for the case with enum instead of pattern, this is not true. Consider the following example:

{
  "type": "object",
  "title": "workingHours",
  "definitions": {
    "weekdays": {"type": "string", "enum": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]}
  },
  "additionalProperties": {"type": "number"},
  "propertyNames": {"$ref": "#/definitions/weekdays"}
}

could well be expressed in TS as

enum weekdays {
  monday = "monday",
  tuesday = "tuesday",
  wednesday = "wednesday",
  thursday = "thursday",
  friday = "friday",
  saturday = "saturday",
  sunday = "sunday"
}
type workingHours = {[k in weekdays]: number};

The example also shows what would be the purpose of this instead of specifying the properties literally: weekdays does not have to be repeated all the time when there are more types making use of its keys.

Remirror-zz avatar Sep 08 '20 18:09 Remirror-zz

Note that properties expressed with additionalProperties are optional so the correct expression in TS is:

type workingHours = {[k in weekdays]?: number};

johnbillion avatar Dec 06 '20 17:12 johnbillion