#Why this makes an error?

33 messages · Page 1 of 1 (latest)

celest atlasBOT
#
OnkelTem#4669

Preview:```ts
type A = {
foo: {
fooA: ["1"]
fooB: ["2"]
}
bar: {
barA: ["10"]
}
}

declare function asd<
T extends keyof A,
P extends keyof A[T],
S extends A[T][number] // Why this makes error?

(): void```

turbid tapir
#

Hi folks. I cannot get why it raises an error

#
Type 'number' cannot be used to index type 'A[T]'.(2536)
#

How so?
If I do it by parts, it works

#

erm, a typo, one moment

celest atlasBOT
#
OnkelTem#4669

Preview:```ts
type A = {
foo: {
fooA: ["1"]
fooB: ["2"]
}
bar: {
barA: ["10"]
}
}

declare function asd<
T extends keyof A,
P extends keyof A[T],
S extends A[T][P][number] // Why this makes error?

(): void

type R1<
T extends keyof A,
P extends keyof A[T]

= A[T][P]
...```

turbid tapir
#

So type RR = R1<"foo", "fooA"> correctly fetches ["1"]

#

Then why I cannot index it with number?

#

Or even this:

celest atlasBOT
#
OnkelTem#4669

Preview:```ts
type A = {
foo: {
fooA: ["1"]
fooB: ["2", "3"]
}
bar: {
barA: ["10"]
}
}

declare function asd<
T extends keyof A,
P extends keyof A[T],
S extends A[T][P][number] // Why this makes error?

(): void

type R1<
T extends keyof A,
P extends keyof A[T]

= A[T][P]
...```

turbid tapir
#

As you see, the cases thing shows that it's being fetched correctly

#

I can even flaten it further:

type R2 = cases[number]
type R3 = R2[number] // type R3 = "1" | "2" | "3" | "10"
#

Ah, I think I got it

#

So this one works:

celest atlasBOT
#
OnkelTem#4669

Preview:```ts
type A = {
foo: {
fooA: ["1"]
fooB: ["2", "3"]
}
bar: {
barA: ["10"]
}
}

declare function asd<
T extends keyof A,
P extends keyof A[T]

(t: T, p: P, s: A[T][P]): void

asd("foo", "fooB", ["2", "3"])```

turbid tapir
#

But it fetches ["2", "3"]. While I need to make a union from it.

#

But it doesn't allow me to make it:

celest atlasBOT
#
OnkelTem#4669

Preview:```ts
type A = {
foo: {
fooA: ["1"]
fooB: ["2", "3"]
}
bar: {
barA: ["10"]
}
}

declare function asd<
T extends keyof A,
P extends keyof A[T]

(t: T, p: P, s: A[T][P][number]): void

asd("foo", "fooB", "2")```

turbid tapir
#

What the heck, folks?

celest atlasBOT
#
n_n#2622

Preview:```ts
...
declare function asd<
T extends keyof A,
P extends keyof A[T]

(
t: T,
p: P,
s: Extract<A[T][P], unknown[]>[number]
): void
...```

bitter elbow
#

@turbid tapir

#

tl;dr typescript isn't smart enough

turbid tapir
#

But it already knows that A[T][P] is a union of arrays

#

so taking [number] from it should result to union of elements of arrays

#

How can I do it anyway? I'm really out of ideas

bitter elbow
bitter elbow
turbid tapir
#

Oh, damn, I missed it sorry

#

Oh my gosh, it's magic!

#

How do you know that you should have extracted exactly that guy? 🙂

#

unknown[]

bitter elbow
#

(well technically readonly unknown[] is wider)