0

I was trying to receive the autocompletion of a nested object from a function but I just can't make it work.

Example:

I have the tree object above.

const tree = {
  branch1: {
    leaf1: {
      bug1: "ant",
    },
  },
  branch2: {
    leaf2: {
      bug2: "ladybug",
    },
  },
};

and the above function with some types:

type TreeKeys = keyof typeof tree;
type LeafKeys = keyof typeof tree[TreeKeys];

const useTree = (branchName: TreeKeys, bugName: LeafKeys) => {
  return tree[branchName][bugName];
};

Is it possible to get the autocomplete for this case?

const { bug2 } = useTree("branch2","leaf2");

I expected branch2, leaf2 and bug2 to be autocompleted, but only branch2 does.

1 Answer 1

1

Make both arguments generic, so that TypeScript can determine the possible output types depending on the argument passed in.

const tree = {
  branch1: {
    leaf1: {
      bug1: "ant",
    },
  },
  branch2: {
    leaf2: {
      bug2: "ladybug",
    },
  },
};
type Tree = typeof tree;
type TreeKeys = keyof Tree;
const useTree = <T extends TreeKeys, U extends keyof Tree[T]>(branchName: T, bugName: U) => {
  return tree[branchName][bugName];
};
const { bug2} = useTree("branch2","leaf2" as const);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.