gustavoguichard / string-ts

Strongly typed string functions
MIT License
1.19k stars 17 forks source link

[QUESTION]: Removing the `IsStringLiteral` check from certain string utilities might make the types more precise #241

Open som-sm opened 2 months ago

som-sm commented 2 months ago

So, the TrimStart utility when instantiated with any infinite string type like string, Uppercase<string>, on${Capitalize<string>} etc returns string.

type test1 = Expect<Equal<TrimStart<string>, string>>
type test2 = Expect<Equal<TrimStart<Uppercase<string>>, string>>
type test3 = Expect<Equal<TrimStart<`on${Capitalize<string>}`>, string>>
type test4 = Expect<Equal<TrimStart<`  hey, ${string}`>, string>>

This behaviour is surely not incorrect, but feels like we can make the types more precise just by removing the IsStringLiteral check.

export type TrimStart<T extends string> = T extends ` ${infer rest}`
  ? TrimStart<rest>
  : T

Which means we now get more precise types:

type test1 = Expect<Equal<TrimStart<string>, string>>
type test2 = Expect<Equal<TrimStart<Uppercase<string>>, Uppercase<string>>>
type test3 = Expect<Equal<TrimStart<`on${Capitalize<string>}`>, `on${Capitalize<string>}`>>
type test4 = Expect<Equal<TrimStart<`  hey, ${string}`>, `hey, ${string}`>>

So, the first three cases return back exactly the same type they received, while the last case correctly removes the leading spaces from the input string, resulting in more precise types without being inaccurate.

gustavoguichard commented 2 months ago

Hey @ssmkhrj , thanks for the message and effort!

You may be completely right here. We have made a lot of code changes to every method when we introduced IsStringLiteral and certain methods might not need them.

Whenever I have some sparing time I'll check your supposition but feel free to send a PR in the meantime. If you do so, make sure the tests are successful (the CI will ultimately tell us) and your use case is covered ;)

Cheers