Created
March 1, 2020 22:18
-
-
Save brayhoward/1954d6df9df06f213c568adc1002415a to your computer and use it in GitHub Desktop.
Example of using Typescript keyof operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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