#Narrow nested object based on value type

4 messages · Page 1 of 1 (latest)

cinder flame
#

I'm looking for a way to take a nested object type and narrow it to just the leaf keys where their value is type T

type Input = {
  str: string,
  other: {
    int: number
  },
  foo: {
    bar: number,
    baz: string  
  },
}

// DeepNarrowByType<Input, string>; ???

type Output = {
  str: string,
  foo: {
    baz: string  
  },
}
prisma portal
#

something like this?

heady hamletBOT
#
that_guy977#0

Preview:ts ... type DeepNarrowByType<T, V> = T extends V ? T : { [K in keyof T as T[K] extends V ? K : T[K] extends object ? {} extends DeepNarrowByType<T[K], V> ? never : K : never]: DeepNarrowByType<T[K], V> } ...

cinder flame
#

Aha yes. That's it. I couldn't quite work out the syntax for recursively narrowing. Thank you.