简体   繁体   中英

How to access the type of object's value by its key?

So I have a function that returns a function. I want to have this:

fn: <T extends Object>(key: keyof T) => (value: ???) => void

What I want for ??? to be the type of instanceOfT[key] . For example, if T={name: string; age: number} T={name: string; age: number} I want fn('name') to return (value: string) => void and for fn('age') to return (value: number) => void

Is that even possible?

Unfortunately, it is not possible to partially infer generic type of your function. See GitHub issues:

You need to use one of workarounds:

  • Curry
  • Pass a dummy parameter
  • Specify all parameters as generic arguments

See answer to In TypeScript is it possible to infer string literal types for Discriminated Unions from input type of string?

namespace Curry {
  type Consumer<K> = (value: K) => void;

  function makeConsumer<P>()/*: <K extends keyof P>(key: K) => Consumer<P[K]>*/ { 
    function factory<K extends keyof P>(key: K): Consumer<P[K]> {
      return (value: P[K]) => console.log(value);
    }
    return factory;
  }
  const barConsumer = makeConsumer<{ bar: string }>()("bar");
}


namespace Dummy {
  type Consumer<K> = (value: K) => void;

  function makeConsumer<P, K extends keyof P>(dummy: P, key: K): Consumer<P[K]> { 
    return (value: P[K]) => console.log(value);  
  }
  type T = { bar: string };
  const barConsumer = makeConsumer(null! as T, 'bar');
}


namespace AllParamsInGeneric {
  type Consumer<K> = (value: K) => void;

  function makeConsumer<P, K extends keyof P>(): Consumer<P[K]> { 
    return (value: P[K]) => console.log(value);  
  }
  const barConsumer = makeConsumer<{ bar: string }, 'bar'>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM