#Help mapping a complex type into another type

10 messages · Page 1 of 1 (latest)

eager mortar
#

I've been trying to create a Generic type that could do the following:

// Given types that looks like this
interface ModelBase {
  general: {
    a: string;
    b: string;
  }
};

interface ModelA extends ModelBase {
  c: [string, string];
  d: [string, number];
  e: [string, Record<string,any>];
};

interface ModelB extends ModelBase {
  f: [string, number];
  g: [string, boolean]; 
};


// Write a Generic, which could do the following
// Take any of ModelA or ModelB, and convert it to the following
type ConvertedModelA = {
  c: string;
  d: number;
  e: string; // Record first parameter
}

type ConvertedModelB = {
  f: number;
  g: boolean;
}

I've tried mapping the other way around, but realised I would have issues with converting string, because I wouldn't be able to tell if string should be transformed into string or Record<string,any>

I have no idea on how to extract the second part of the arrays and how to get just the Record first argument.

gloomy tree
#

oh actually im not sure you can error

#

hm, maybe you can.

#

here's one that assumes that all the extra props are valid

silk barnBOT
#
that_guy977#0

Preview:ts ... type Convert<T extends ModelBase> = { [K in keyof Omit<T, keyof ModelBase>]: T[K] extends [ string, infer V ] ? V extends object ? keyof V : V : never } ...

gloomy tree
#

you could replace that never with T[K] to passthrough any non-tuple props, or you could have a conditoinal in the key to remove the prop

#

here's one that restricts the passed type

silk barnBOT
#
that_guy977#0

Preview:```ts
...
type Convert<
T extends ModelBase & Record<U, [string, unknown]>,
U extends string = keyof Omit<T, keyof ModelBase> &
string

= {
[K in keyof Omit<T, keyof ModelBase>]: T[K] extends [
string,
infer V
]
? V extends object
? keyof V
: V
: never
}
...```

eager mortar
#

Thanks!