Home > OS >  TypeScript Generic Type in getDeepValue
TypeScript Generic Type in getDeepValue

Time:07-28

Here are the correct code snippets:

export const getDeepValue = <T, TFK extends keyof T, TSK extends keyof T[TFK]>(
  obj: T,
  firstKey: TFK,
  secondKey: TSK
) => {
  return obj[firstKey][secondKey];
};
const obj = {
  foo: {
    a: true,
    b: 2,
  },
  bar: {
    c: "12",
    d: 18,
  },
};

const value = getDeepValue(obj, "foo", "a");

Here are my version of getDeepValue:

export const getDeepValue = <T, >(
  obj: T,
  firstKey: keyof T,
  secondKey: keyof T[keyof T]
) => {
  return obj[firstKey][secondKey];
};

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

const value = getDeepValue(obj, "foo", "a");

And my code always give me an error that secondKey is never type.

What's different between using extends or not using it?

Why can't I use keyof T[keyof T] for secondKey?

CodePudding user response:

T[keyof T] doesn't work because Typescript cannot infer that the parameter keyof T is the same as the return keyof T.

You can use a second type parameter U that extends keyof T and adjust the return type to T[U], which infers that the parameter keyof T is the same as the return keyof T

export const getDeepValue = <T,U extends keyof T>(
  obj: T,
  firstKey: U,
  secondKey: keyof T[U]
) => {
  return obj[firstKey][secondKey];
};

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

const value = getDeepValue(obj, "foo", "a");
  • Related