Reputation: 31
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
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