Skip to content

Instantly share code, notes, and snippets.

@jclem
Created November 30, 2018 17:31
Show Gist options
  • Save jclem/4600427378e67b67bc9b566f6aeea2b3 to your computer and use it in GitHub Desktop.
Save jclem/4600427378e67b67bc9b566f6aeea2b3 to your computer and use it in GitHub Desktop.
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