#Simple conditional type as return type doesn't seem to work

44 messages · Page 1 of 1 (latest)

lament snow
#

typescript cannot typecheck conditional return types

#

you will need to use as

fleet prism
#

you can try no matter what I did all fail

lament snow
#

as any

#

return (Math.random()>0.5 ? 1:2) as any;

fleet prism
#

as any yeah that might work. But as you say it seems TS has problems with conditional return types

#

Even this fails

lament snow
#

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

naive ruin
#
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...

lament snow
#

if you want the default to be different then you need to provide your own default

knotty stag
#

or just use overloads

lament snow
#

ohhhh

#

i forgor

knotty stag
#

conditional returns/params almost never work

lament snow
#

yes overloads are safer

knotty stag
#

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

lament snow
#

with overloads you wont accidentally explicitly provide the type even though you don't pass sk

fleet prism
lament snow
fleet prism
#

Aah I see. Althoug this: T extends number ? T : Twas a bit different case because T might not extend number.

lament snow
#

because the false case is T

fleet prism
#

Yeah both result is T

#

That's what you meant

lament snow
#

yeah

fleet prism
#

But yeah these return types really don't work in most of the cases

#

with conditionals I mean

lament snow
#

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)

fleet prism
#

but it shouldn't error imho

fleet prism
lament snow
#

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)

fleet prism
#

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

lament snow
#

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

fleet prism
#

I see

fleet prism
lament snow
#

yeah, exactly