【问题标题】:How to access the type of object's value by its key?如何通过其键访问对象的值的类型?
【发布时间】:2020-04-15 21:55:49
【问题描述】:

所以我有一个返回函数的函数。我想要这个:

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

我希望??? 成为instanceOfT[key] 的类型。例如,如果 T={name: string; age: number} 我希望 fn('name') 返回 (value: string) => void 并希望 fn('age') 返回 (value: number) => void

这可能吗?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    很遗憾,无法部分推断出函数的泛型类型。请参阅 GitHub 问题:

    您需要使用其中一种解决方法:

    • 咖喱
    • 传递一个虚拟参数
    • 将所有参数指定为通用参数

    查看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'>();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多