Home > Net >  Higher order type function with nested property access
Higher order type function with nested property access

Time:02-15

Assume I have an interface like below.

interface Nested { 
  x: { b: { c: { d: "e"}}};
  y: { b: { c: { d: "f"}}};
}

It is possible to generate two types from it as below.

type E = Nested['x']['b']['c']['d'];
type F = Nested['y']['b']['c']['d'];

However I would like to avoid repeating ['b']['c']['d'] each time, and instead do something like

type E = NestedBCD<'x'>
type F = NestedBCD<'y'>

Basically, a higher order function of sort that operate on types. Is something like this possible in Typescript?

TS Playground

CodePudding user response:

You can do this with type aliases:

interface Nested { x: { b: { c: { d: 'e'}}}, y: { b: { c: { d: 'f'}}}}

type NestedBCD<T extends keyof Nested> = Nested[T]["b"]["c"]["d"];
type E = NestedBCD<"x">;
type F = NestedBCD<"y">;

Playground link

  • Related