Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
You can’t perform that action at this time.