Constrain one Typescript generic parameter based on properties of another?

后端 未结 2 329
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 08:34

I\'m trying to write a function that takes an object and a (string) key, then operates on a property of the object. This is easy:

function f

        
2条回答
  •  醉话见心
    2021-01-22 09:11

    You should extends from keys that result in a value of type number.

    export type PickByValue = Pick<
      T,
      { [Key in keyof T]-?: T[Key] extends ValueType ? Key : never }[keyof T]
    >;
    
    function f>(obj: T, key: K) : T[K] {
      return obj[key]
    }
    

    Edit: What you're trying to do is not possible in TS AFAIK, and sometimes there's a good reason for that. let's suppose you have below code:

    function f>(obj: T, key: K) {
        obj[key] = 5; // Type 'number' is not assignable to type 'T[K]'.
    } 
    
    const obj = {a: 9} as const;
    
    f(obj, "a")
    

    For example in the above scenario, value of property a is a number however it's not of type number but of type 9. there's no way for typescript to know this before hand. in other scenarios, the only thing that comes to my mind is using Type Assertions.

提交回复
热议问题