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

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

Open
som-sm opened this issue Sep 8, 2024 · 1 comment

Comments

@som-sm
Copy link

som-sm commented Sep 8, 2024

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
Copy link
Owner

gustavoguichard commented Sep 9, 2024

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

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

2 participants