Demo: https://tsplay.dev/Nnavaw
So I have an array with the following definition:
Array<{
id?: string;
text?: string;
date?: Date;
}>
That interfers with the following implementation:
data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>
How can I tell Typescript that the Array can also include other properties other than Partial<Record<K, string>> & Partial<Record<H, string | number | null>>?
Because if I'll pass an array with the following defintion it gives me this error:
Type 'Date' is not assignable to type 'string | number | null | undefined'.
Complete function:
ifAlreadyExistsString<K extends PropertyKey, H extends PropertyKey>(
data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>,
key: K,
value: string,
idKey?: H,
idValue?: string | number | null
): boolean {
return (
data.filter((item) => {
// If the value is found in the data array
if (item[key] && item[key]?.trim().toLowerCase() === value.trim().toLowerCase()) {
// Then check if the id of the value matches the found entry
// If the ids are matching, then you are currently editing this exact entry
// If the ids are NOT matching, then you have found a duplicate.
if (idKey && item[idKey] && idValue) {
return !(item[idKey] === idValue);
} else {
// If no idKey is provided, then we have found a duplicate.
return true;
}
}
return false;
}).length !== 0
);
}
data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | Date | null>>>fixes the error. Is that what you wanted?idKey/H. The sturcture of the object could be anything but should include the Record definitionsidKeyis not passed. Two options I see; use overloads like this, or use aNoInfertrick to try to preventdatafrom being used to inferH, like this. Let me know which, if any, of those meets your needs and I will write up an answer explaining. If neither meets your needs, what am I missing?NoInfertrick works fine, thank you!