Skip to content

Instantly share code, notes, and snippets.

@brayhoward
Created March 1, 2020 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brayhoward/1954d6df9df06f213c568adc1002415a to your computer and use it in GitHub Desktop.
Save brayhoward/1954d6df9df06f213c568adc1002415a to your computer and use it in GitHub Desktop.
Example of using Typescript keyof operator
interface RecursiveArray<T> extends Array<T | RecursiveArray<T>> {}
function getLast<O extends object, K extends keyof O>(
mapOrList: O | RecursiveArray<O>,
key: K
): O[K] | null {
if (!mapOrList) return null;
if (Array.isArray(mapOrList)) {
return getLast(mapOrList.reverse().find(m => !!getLast(m, key))!, key);
}
return mapOrList[key];
}
getLast({color: "green"}, "color" ) // "green"
getLast([{color: "red"}], "color"); // Argument of type '"color"' is not assignable to parameter of type 'never'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment