【问题标题】:Type for all keys which would give numeric values键入所有会给出数值的键
【发布时间】:2022-07-18 23:08:18
【问题描述】:

假设我想编写一个sortBy 函数,它采用Ts 的列表和T 的键来对列表进行排序。

为了正常工作,我希望该键只接受 T 的数字键。

我有这个,但我不知道如何限制Key,以便T[Key] 引用一个数字:

const sortBy = <T, Key extends keyof T>(items: T[], key: Key) { 
  // impl
}

我玩过这个,但无法让它工作:

type NumericAttributesOf<T> = {
  [K in keyof T]: T[K] extends number ? T[K] : never
}

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    它似乎对我有用,我想你忘记了 sortBy 函数中的箭头 =&gt;

    type NumericAttributesOf<T> = {
      [K in keyof T]: T[K] extends number ? T[K] : never
    }
    
    //                                                                           ||
    //                                                                           VV
    const sortBy = <T, Key extends NumericAttributesOf<T>>(items: T[], key: Key) => { 
      // impl
    }
    
    sortBy([{
      name: 'Test',
      age: 20
    }], 'name') // ERROR
    
    sortBy([{
      name: 'Test',
      age: 20
    }], 'age') // Ok
    

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 2021-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      相关资源
      最近更新 更多