Rodolfo Vieira
Rodolfo Vieira

Reputation: 31

How do I type nested objects with typescript?

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.

Upvotes: 0

Views: 124

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371193

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);

Upvotes: 1

Related Questions