【问题标题】:Infer exact object property type when returning it via function通过函数返回时推断确切的对象属性类型
【发布时间】:2021-10-05 20:30:20
【问题描述】:

给定以下状态:

  type DataType = {
        a: string,
        b: number,
        c: boolean
  }

  const testObject: DataType = {
        a: 'Dummy',
        b: 1,
        c: true
  }

  type A = typeof testObject['a'] // string
  type B = typeof testObject['b'] // number
  type C = typeof testObject['c'] // boolean

很明显,我可以使用typeof testObject['a']DataType['a'] 来获取DataType 对象的每个属性的类型。

但是, 当我尝试通过函数内部的访问器执行相同操作时,我无法获得我正在访问的属性的确切类型。下面的例子:

  function testAccess<T>(o: T, p: keyof T): T[typeof p] {
        return o[p]
  }

  const a = testAccess(testObject, 'a') // string | number | boolean

我是否遗漏了什么,有什么方法可以将类型缩小到我们发送的确切密钥?

TS 游乐场链接:https://www.typescriptlang.org/play?jsx=0#code/C4TwD...

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    诀窍是将键类型作为通用参数包含在内:

    function testAccess<T, P extends keyof T>(o: T, p: P): T[P] {
          return o[p]
    }
    
    const a = testAccess(testObject, 'a') // string
    

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2013-02-17
      • 2020-04-14
      • 1970-01-01
      • 2021-06-11
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多