ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.47k stars 31 forks source link

Issue with CompilerOptions.keyofStringsOnly = true #16

Closed stalniy closed 3 years ago

stalniy commented 3 years ago

The issue

FromSchema does not infer required properties when compilerOptions.keyofStringsOnly = true.

The reason

I'm working on a project where ts compiler option keyofStringsOnly is set to true. This makes keyof WHATEVER to return string type instead of string | number | symbol. That's why when you check whether number extends keyof S["required"] on this line, it return false.

In general, keyof operator is not safe to test whether type is an array or tuple because even for objects and interfaces it returns string | number.

Also if you check the output type of type indexesOfArray = keyof string[], you will see that ts returns number and names of all methods. Even keyof ReadonlyArray<string> because it contains numeric indexes, length and all non mutating array methods

How to fix

In order to fix the issue, you need to convert that and similar checks to check on ReadonlyArray<string> or on { length: number }

type GetRequired<S> = "required" extends keyof S
  ? S["required"] extends ReadonlyArray<string>  // <----
    ? S["required"][number]
    : never
  : never;
stalniy commented 3 years ago

any thoughts?

ThomasAribart commented 3 years ago

Good catch ! I'll have a look into it next week !

stalniy commented 3 years ago

I can create a PR if you are ok with the fix, so the only thing you need to do is to release a new version :) Please, it's quite critical for me and I don't want to create hack-arounds

ThomasAribart commented 3 years ago

@stalniy It's merge and deployed in v1.6.1 👍 Thanks for your contribution !

stalniy commented 3 years ago

Awesome! Thank you!