#Can someone help me understand this generic result?

20 messages · Page 1 of 1 (latest)

molten loom
#
type X<G> = any extends G ? 1 : 0;

type Y = X<string>; // 1 | 0 ???

Why is X<string> equal to the union of 1 | 0 instead of just one or zero?

acoustic rapids
#

probably weird effects of any, in short

#

idk what exactly is going on there but i'm pretty sure it's related to the any

molten loom
#

What I'm trying to achieve is to check if the provided generic type is any and not other type, but this makes my life harder 🥲

acoustic rapids
#

any won't work like that

#

generally you use conflicting conditionals to achieve that, such as T extends never then unknown extends T, or T & 1 extends 0

molten loom
#

ok, will try this

#

This solution seems to work for my case:

type X<G> = never extends G ? unknown extends G ? 1 : 0 : 0;

type W = X<any>; // 1
type Y = X<unknown>; // 1
type A = X<never>; // 0
type Z = X<string>; // 0
acoustic rapids
#

i mean, that doesn't exactly check for any

#

never extends G is a tautology

#

unknown extends G checks for exactly unknown and any

#

never extends T, T extends unknown, any extends T, and T extends any are all always true

molten loom
#

oh, thanks for these examples

#

then I'll use the unknown and any version, it's ok for my use case

#

!resolved

molten loom
#

Great image representations

hollow fox
#

its a good blog post

acoustic rapids