#Recursive type to convert dates to strings

7 messages · Page 1 of 1 (latest)

tropic raptor
#
wild escarpBOT
#

@tropic raptor Here's a shortened URL of your playground link! You can remove the full link from your message.

andrewray#2183

Preview:```ts
type Dated<T> = T extends Date
? string
: T extends any[]
? Dated<T>[]
: T extends object
? {[key in keyof T]: Dated<T[key]>}
: T

export const sanitizeDates = <T>(
value: T
): Dated<T> => {
if (Array.isArray(value)) {
const mapped =
value.map<
T extends (infer U)[] ? Dated<U> : never
>(sanitizeDa
...```

round compass
#

i've gotta run and this isn't a complete answer, but thought it might be helpful:

here's an adjusted Dated type:

type Dated<T> = T extends Date
  ? string
  : T extends readonly unknown[]
  ? readonly Dated<T[number]>[]
  : T extends object
  ? { [key in keyof T]: Dated<T[key]> }
  : T;

there are a few changes from yours:

  1. check for readonly arrays. regular arrays extend readonly arrays, but not the other way around. your type would have misbehaved if somebody provided a type inferred from an as const array variable, for example
  2. fix the element type for the mapped array. similar to how you do Dated<T[key]> in the object case, the array you return needs to recursively update the element type, not the array itself (otherwise it just keeps recursing until it hits the depth limit)

you might also want to add more cases to maintain readonly-ness of arrays (don't add it to non-readonly ones) and perhaps to map over heterogeneous tuple types (like [Date, string, number, Date])

#

actually it might be possible to simplify down to a homomorphic mapped type to handle all of those cases. give this a try and see if it has the behavior you want for arrays/objects/etc:

type Dated<T> = T extends Date ? string : { [key in keyof T]: Dated<T[key]> };
#

ok now i really gotta run. good luck with the runtime stuff, i didn't have time to look at that

tropic raptor
#

Thank you, it's actually not the type that I"m having trouble with, it's the function to convert the object to the type

round compass
#

yeah, i see there are other problems there, but your function couldn't have possibly worked for arrays with that type unless it returned something like [[[[[[[[[[[[[[[[[[[blah]]]]]]]]]]]]]]]]]]]