Skip to content

Instantly share code, notes, and snippets.

@kasper573
Created March 1, 2021 22:39
Show Gist options
  • Save kasper573/00290cb52f03cf010a911e8ddc512bad to your computer and use it in GitHub Desktop.
Save kasper573/00290cb52f03cf010a911e8ddc512bad to your computer and use it in GitHub Desktop.
type A = number;
type B = string;
type Lists = {
a: A[];
b: B[];
};
export const selectList = <ListName extends keyof Lists>(
listName: ListName
): Lists[ListName] => {
switch (listName) {
case "a":
return [1, 2, 3] as Lists[ListName]; // Gives error if i don't cast
case "b":
return ["a", "b", "c"] as Lists[ListName]; // Gives error if i don't cast
}
return []; // Gives error if i don't return (which I shouldn't need to since above switch exhausts all return options)
};
@lumie1337
Copy link

lumie1337 commented Mar 1, 2021

This works:

type A = number;
type B = string;

type Lists = {
  a: A[];
  b: B[];
};

function selectList<E extends keyof Lists>(listName: E): Lists[E];
function selectList(
  listName: keyof Lists
): Lists[typeof listName] {
  switch (listName) {
    case "a":
      return [1, 2, 3];
    case "b":
      return ["a", "b", "c"]
  }
};

const s = selectList("a")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment