#Generics within JSON like structure

9 messages · Page 1 of 1 (latest)

orchid kindle
#

Imagine this structure:

[
  {
    name: "Tailor",
    text: "any string",
  }, {
    name: "Avi",
    text: "any string",
  }, {
    name: "Yehoshua",
    text: "any string",
  }
]

Now, there's a function that takes that data and converts it into the following structure:

{
   Tailor: "the `text`",
   Avi: "the `text`",
   Yehoshua: "the `text`",
}

How would you implement this using generics in order to preserve the type?

trail zenith
#

Do you need to preserve the values of text?

steel gyro
#

@orchid kindle what do you mean "generics to preserve the types"?

#

want a type to replicate what your function is doing, but at a type level?

orchid kindle
dapper pikeBOT
#
nonspicyburrito#0

Preview:```ts
declare function transform<
const T extends readonly { name: string; text: string }[],

(
data: T,
): {
[V in T[number] as V['name']]: V['text']
}

const result = transform([
{
name: 'Tailor',
text: 'foo',
},
{
name: 'Avi',
...```

#
nonspicyburrito#0

Preview:```ts
declare function transform<
const T extends readonly { name: string; text: string }[],

(data: T): Record<T[number]['name'], string>

const result = transform([
{
name: 'Tailor',
text: 'foo',
},
{
name: 'Avi',
text: 'bar',
...```

#
ascor8522#0

Preview:```ts
const input = [
{
name: "Tailor",
text: "any string",
},
{
name: "Avi",
text: "any string",
},
{
name: "Yehoshua",
text: "any string",
},
] as const

type Transform<
Arr extends ReadonlyArray<{
name: string
text: string
}>

= {
[K
...```

orchid kindle