Created
November 30, 2018 17:31
-
-
Save jclem/4600427378e67b67bc9b566f6aeea2b3 to your computer and use it in GitHub Desktop.
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
const data = { | |
numbers: [1, 2, 3], | |
strings: ['a', 'b', 'c'], | |
notNumbers: 'Hello, world.' | |
} | |
deleteFromArray(data, 'numbers', num => num === 2) | |
function deleteFromArray<O, K extends keyof O, T>( | |
obj: O, | |
key: O[K] extends Array<T> ? K : never, | |
func: O[K] extends Array<T> ? (v: O[K][0]) => boolean : never | |
) { | |
const arr = obj[key] | |
// Why is this necessary if a value is only assignable | |
// to `key` if `obj[key]` is an array? | |
if (!Array.isArray(arr)) { | |
throw new Error('Value is not an array') | |
} | |
return arr.filter(v => !func(v)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment