#Literal array inference

29 messages · Page 1 of 1 (latest)

autumn arch
#
const poeple = [
  { name: 'john', age: 20 },
  { name: 'jane', age: 30 },
] as const

type NameArray = typeof poeple[number]['name'][]
// I want this to be ['john', 'jane'] or ['jane', 'john'] instead of ('john' | 'jane')[]```
placid wren
#

not really possible

#

you can't go from an union to a tuple

#

in an union, the order doesn't matter, whereas it (technically) would in a tuple

dreamy pendant
#

pretty sure you can though

placid wren
#

could use something like

type TupleUnion<U extends string, R extends any[] = []> = {
    [S in U]: Exclude<U, S> extends never ? [...R, S] : TupleUnion<Exclude<U, S>, [...R, S]>;
}[U];
dreamy pendant
#

typeof poeple is a tuple, you can map it

placid wren
dreamy pendant
#

!ts Names

#

whoops that is definitely not right

dreamy pendant
placid wren
#

different types for different purposes

dreamy pendant
#

where is a union relevant here

#

they haven't said what it's for

autumn arch
#

Pretty much I want to make a type in zod where it has to be a key of an object

This doesn't work:
game: z.enum(Object.keys(GAMES) as (keyof typeof GAMES)[]),

#

I was going to use .refine but I don't know how to get that keyof type inference after the schema is parsed

vestal tulip
#

[number] is lossy, so don't do that

jagged egretBOT
#
Chen Sida#0813

Preview:```ts
const people = [
{name: "john", age: 20},
{name: "jane", age: 30},
] as const

type NameArray<T extends readonly {name: string}[]> = {
[K in keyof T]: T[K]["name"]
}
type A = NameArray<typeof people>
// ^?```

vestal tulip
#

A more extensible version, if you want:

jagged egretBOT
#
Chen Sida#0813

Preview:```ts
const people = [
{name: "john", age: 20},
{name: "jane", age: 30},
] as const

type TupleProps<
T extends readonly {[K in P]: string}[],
P extends string

= {[K in keyof T]: T[K][P]}
type A = TupleProps<typeof people, "name">
// ^?```

vestal tulip
#

Of course, if you also want to deduplicate, then U2T is your friend:

jagged egretBOT
#
Chen Sida#0813

Preview:```ts
import type {U2T} from "type-collections"

const people = [
{name: "john", age: 20},
{name: "jane", age: 30},
{name: "john", age: 30},
] as const

type TupleProps<
T extends readonly {[K in P]: string}[],
P extends string

= U2T<T[number][P]>
...```

autumn arch
#

Thanks

#

!resolved

tropic bane
#

then u got u2t

placid wren