Skip to content

Template Literal String Types are converted to an array schema instead of a string #426

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

Closed
ssc-hrep3 opened this issue Jun 17, 2021 · 3 comments

Comments

@ssc-hrep3
Copy link

ssc-hrep3 commented Jun 17, 2021

Template Literal String Types are converted to an array schema. They should, however, be converted to strings with a pattern matching the template literal (or at least to a regular string).

Here is an example of a template literal:

export const Test = `${number}`;

This type is then generated to:

{
  "type": "array",
  "items": {
    "type": "string"
  }
}

It should, however, at least be converted to this instead:

{
  "type": "string"
}

Even better would be if the template literal string is converted to a valid pattern. But this might be rather complex (joining regular expressions from types used within the template literal with the static string).

{
  "pattern": "^-?[1-9]\d*(?:\.\d+)?$"
  "type": "string"
}

A temporary workaround is to use the JSDoc annotation @type string, but unfortunately this does not work everywhere (i.e. when the template literal types are being used directly in arrays) due to another bug (see #425).

Version: 0.50.1
Schema Generation Settings:

{
  ref: false,
  required: true,
  noExtraProps: true,
  validationKeywords: ['errorMessage'],
  titles: true,
  uniqueNames: true,
  rejectDateType: true
}
@ssc-hrep3 ssc-hrep3 changed the title Template Literal Strings are converted to an array schema instead of a string Template Literal String Types are converted to an array schema instead of a string Jun 17, 2021
@olafur-palsson
Copy link

Related is using a template literal inside a template literal and getting 'TemplateLiteral' only refers to a type, but is being used as a value here. can be fixed by updating.

@derekslarson
Copy link

Facing the same issue in 0.51.0

@slhck
Copy link

slhck commented Feb 16, 2023

@YousefED Any idea on how to solve this? Still getting this.

Note that as a workaround you may use ts-json-schema-generator:

export type Test = {
    foo: `${number}x${number}`;
}

Then ts-json-schema-generator --path test.ts returns:

{
  "$ref": "#/definitions/Test",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Test": {
      "additionalProperties": false,
      "properties": {
        "foo": {
          "type": "string"
        }
      },
      "required": [
        "foo"
      ],
      "type": "object"
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants