[Typescript] Tips: Use 'extends' keyword to narrow the value of a generic

export const getDeepValue = <Obj, FirstKey extends keyof Obj, SecondKey extends keyof Obj[FirstKey]>(
  obj: Obj,
  firstKey: FirstKey,
  secondKey: SecondKey
): Obj[FirstKey][SecondKey] => {
  return {} as any
}

const obj = {
  foo: {
    a: true,
    b: 2
  },
  bar: {
    c: "cool",
    d: 2
  }
}

const result = getDeepValue(obj, "bar", "d")

 

posted @ 2022-10-03 18:10  Zhentiw  阅读(4)  评论(0编辑  收藏  举报