-
Notifications
You must be signed in to change notification settings - Fork 12.8k
feat: refine .split() return type #56834
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
Conversation
Signed-off-by: Andres Correa Casablanca <castarco@coderspirit.xyz>
@microsoft-github-policy-service agree |
I found two: |
Your changed type definitions fail with |
NOTE: I edited this post to correct an incorrect statement I made a few minutes ago. Yes, I noticed some time later 😞 . I was thinking if it was possible to cover those corner cases with some extra function overrides... but that won't be possible (for now), because there's a more generic case quite difficult to cover: const strValue = ''
const a = strValue
const b = strValue
function myUselessFunction(x: string, y: string): string[] {
// Because we don't know the values of `x` and `y`, we can't produce
// any reliable inference on the result's type :( .
return x.split(y)
}
const c = myUselessFunction(a, b) So I guess I'll have to close this one. As a side note, this problem (and other similar ones) could be "mitigated" (but not completely) with any or many of the following features:
Regarding the second option I listed here, we can already do something similar enough with conditional types... but they only work well when used in function params position and its usefulness is very limited: type NonEmptyString<S extends string = string> = S extends '' ? never : S
// The return type won't be enough for TS to know that the returned value is
// not '' once it is used elsewhere. So this way to discriminate against '' is
// only valid at the call site.
function g<S extends string>(s: NonEmptyString<S>): NonEmptyString<S> {
if (s === '') {
throw new Error('simplest way to avoid having to rely on a union return type')
}
return s as NonEmptyString<S>
}
// The type system will complain, but... only for statically-known literals
const vvv = g('') P.S.: We could apply the opposite approach I followed in this PR: instead of trying to consider the cases where the return type is So, if we statically know that our separator is NOT |
My new attempt: #56841 . |
Work in Progress: