#How come this doesn't work?

26 messages · Page 1 of 1 (latest)

odd crowBOT
#
U9G#0670

Preview:```ts
import type {
Equal,
Expect,
NotAny,
} from "@type-challenges/utils"

const elems = [{a: "apple"}, {a: "orange", b: 1}]

const {a, ...rest} = elems[Math.floor(Math.random())]

if (a === "orange") {
type Y = typeof rest.b
type X = Expect<Equal<Y, number>>
...```

rose solstice
#

number | undefined is not the same as number

#

those two types are not compatible

#

so Equal returns false

#

and since Expect is expecting true, you're getting the error

rose solstice
heavy wadi
heavy wadi
rose solstice
#

(even tho your check on the a property also influences the resul on the b property)

#

you should create 2 different types
and use type predicates to tell them appart

#

@heavy wadi

heavy wadi
#

I don't want to make my own types, this data comes from a json

#

idk, im just stuck in somewhere that even the compiler cant help

rose solstice
#

also, since you used object destructuring, those two a and rest variabels are now behaving independenlty for the compiler

odd crowBOT
#
Ascor8522#7606

Preview:```ts
import type {
Equal,
Expect,
} from "@type-challenges/utils"

interface Apple {
a: "apple"
}

interface Orange {
a: "orange"
b: 1
}

type Fruit = Apple | Orange

const elems: Fruit[] = [
{a: "apple"},
{a: "orange", b: 1},
]
const fruit = elems[Math.floor(Math.random())]
...```

rose solstice
#

@heavy wadi

#

also, you need to change Equal<Y, number> to Equal<Y, 1>

#

or define Orange.b as number (and not as 1)

heavy wadi
#

yeah I see the problem

marsh bronze
#
if (a === 'orange') {
    type Y = typeof rest.b
    type X = Expect<Equal<NonNullable<Y>, number>>
}
#

X = true

rose solstice
#

only if the array is declared as const (const elems = [{ a: 'apple' }, { a: 'orange', b: 1 }] as const;)