#Simple conditional type as return type doesn't seem to work
44 messages · Page 1 of 1 (latest)
you can try no matter what I did all fail
as any yeah that might work. But as you say it seems TS has problems with conditional return types
Even this fails
oh yeah that's a bit weird
i know that in some cases typescript widens it to IfTrue | IfFalse
so i wonder why it can't do IfTrue & IfFalse when going the other way
const index = <PK extends string, SK extends string | undefined, R = SK extends undefined ? 1 : 2>(pk: PK, sk?: SK): R => {
return (Math.random() > 0.5 ? 1 : 2) as R;
}
this kinda works? but with const x = index("1") it's still a union...
yes, because generics default to the constraint
if you want the default to be different then you need to provide your own default
or just use overloads
conditional returns/params almost never work
yes overloads are safer
except for validator pattern
if you want to use conditionals in a signature in a way that isn't validation, you probably want overloads instead
with overloads you wont accidentally explicitly provide the type even though you don't pass sk
sorry what you mean here?
oh umm like, T extends (C ? A : B) should be true if T extends A and T extends B
Aah I see. Althoug this: T extends number ? T : Twas a bit different case because T might not extend number.
but it doesn't matter right? because even if it doesn't extend, the resulting type is still T
because the false case is T
yeah
But yeah these return types really don't work in most of the cases
with conditionals I mean
yeah - i'm guessing that's the reason ? T : T doesn't work either
(because if both sides are the same then you might as well remove the entire conditional type completely)
but it shouldn't error imho
I see you mean the reason why it doesn't work is that T and T are same.
nah
logically it should work because T and T are the same
so it doesn't matter whether the extends is true or not
(it shouldn't work in your original case which is ? 1 : 2, because typescript cannot tell that your function body is returning 1 in the appropriate cases)
I meant I was a bit confused here "yeah - i'm guessing that's the reason ? T : T doesn't work either", when you wrote "that's the reason", which reason you were referring to
the reason = because they usually don't work, there's probably no point making it work in a very rare case that should never show up in real code
I see
In the original code I had I think as return type sk extends undefined? 1:2and you say if say sk was undefined, then return type would have been 1, and what if function returned 2 in that case right?
yeah, exactly