Check out this demo: https://tsplay.dev/Nnavaw
I am working with an array that has the following structure:
Array<{
id?: string;
text?: string;
date?: Date;
}>
This conflicts with the current implementation:
data: Array<Partial<Record<K, string>> & Partial<Record<H, string | number | null>>>
How can I inform Typescript that the Array may contain additional properties besides
Partial<Record<K, string>> & Partial<Record<H, string | number | null>>
?
If I try to pass an array with a different definition, it triggers this error message:
Type 'Date' is not assignable to type 'string | number | null | undefined'.
Here is the complete function for reference:
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) => {
// Check if the value exists in the data array
if (item[key] && item[key]?.trim().toLowerCase() === value.trim().toLowerCase()) {
// Verify if the id of the value matches the found entry
// Matching ids means editing existing entry, while non-matching indicates duplicate.
if (idKey && item[idKey] && idValue) {
return !(item[idKey] === idValue);
} else {
// If no idKey is provided, then we have a duplicate entry.
return true;
}
}
return false;
}).length !== 0
);
}