Issue
I want to filter an array, but only filter based on 2 keys (name
& surname
OR n
& s
) out of any possible number of unknown keys
const items = [
{ ..., "n": "John", "s": "Doe" }, // keep - n & s keys are valid
{ ..., "name": "John", "surname": "Doe" }, // keep - name & surname keys are valid
{ ..., "n": "John", "surname": "Doe" }, // remove - n & surname keys are invalid
]
const result = filterValids(items);
// [
// { "n": "John", "s": "Doe", ... }, // seen as valid
// { "name": "John", "surname": "Doe", ...}, // seen as valid
// ]
My solution below does not work
function filterValids(items: (AtLeastOne<shortKeys, longKeys>)[]) {
const filtered: typeof items | [] = [];
for (const item of items) {
const name = item.n || item.name; // name does not exist on `AtLeastOne<shortKeys, longKeys>
const surname = item.s || item.surname; // surname does not exist on `AtLeastOne<shortKeys, longKeys>`
if (checkValidity({name, surname}))
filtered.push(item) // `AtLeastOne<shortKeys, longKeys>` is not assignable to parameter of type `never`
}
return filtered
}
type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U];
type longKeys = {
name: string,
surname: string
}
type shortKeys = {
n: string,
s: string
}
Solution
I have found the solution by using ((shortKeys | longKeys) & { [key: string]: any })[]
const items = [
{ "someKey": "someValue", "n": "John", "s": "Doe" }, // keep - n & s keys are valid
{ "someKey2": "someValue2", "name": "John", "surname": "Doe" }, // keep - name & surname keys are valid
{ "someKey3": "someValue3", "n": "John", "surname": "Doe" }, // remove - n & surname keys are invalid
]
const result = filterValids(items);
// [
// { "n": "John", "s": "Doe", ... }, // seen as valid
// { "name": "John", "surname": "Doe", ...}, // seen as valid
// ]
Solution
function filterValids(items: ((shortKeys | longKeys) & { [key: string]: any })[]) {
const filtered = [];
for (const item of items) {
const name = item.n || item.name;
const surname = item.s || item.surname;
if (checkValidity({name, surname}))
filtered.push(item) //
}
return filtered
}
type longKeys = {
name: string,
surname: string
}
type shortKeys = {
n: string,
s: string
}
Answered By - Kevin Potgieter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.