How can I infer the key used for indexed access type?

I want to create a helper type to infer the key used inside an indexed access type.

Example:

type X = { foo: string, bar: boolean }
type Fn = <T extends X>(value: T) => T["foo"]
type Helper<T> = ???

type Result = Helper<Fn> // should be "foo"

The approach I tried is similar to the built-in ReturnType helper, but doesn't work so far:

type Helper<Fn> = Fn extends (value: infer T) => infer R
  // R extends T[infer Key] does not work: Type 'Key' cannot be used to index type 'T'.
  ? R extends T[keyof T]
    ? T[keyof T]
    : never
  : never

Is this even possible?



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation