like-gold
like-gold2h ago

filter.field is not on type 'CrudFilter' or 'ConditionalFilter'

const { tableProps, filters, sorters } = useTable<UserRecord> const createdAtFilter = filters?.find((filter) => filter.field === 'createdAt')?.value the TS type says filter.field does not exist, but it exists and it works... why?
2 Replies
kapa.ai
kapa.ai2h ago
Hi @khadhulu. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The TypeScript error occurs because the type of each item in the filters array is CrudFilter, which is a union of LogicalFilter and ConditionalFilter. Only LogicalFilter has the field property, while ConditionalFilter does not. The ConditionalFilter is used for logical operators like "or" and "and", and its structure is different—it has an operator and a value (which is an array of filters), but no field property. So, when you do:
filters?.find((filter) => filter.field === 'createdAt')
filters?.find((filter) => filter.field === 'createdAt')
TypeScript complains because filter could be a ConditionalFilter, which does not have a field property. However, at runtime, if your filters only contain LogicalFilter objects, this works as expected. To resolve the type error, you should check if "field" exists on the filter before accessing it:
const createdAtFilter = filters?.find(
(filter) => "field" in filter && filter.field === "createdAt"
)?.value;
const createdAtFilter = filters?.find(
(filter) => "field" in filter && filter.field === "createdAt"
)?.value;
This way, TypeScript knows you're only accessing field on objects that actually have it. This pattern is recommended in the refine documentation and GitHub issues:
The type of filters is correct but you need to check if it is LogicalFilter or ConditionalFilter.
... you can use field key check:
if("field" in filters) {
// in this scope typeof filters will be LogicalFilter[]
}
if("field" in filters) {
// in this scope typeof filters will be LogicalFilter[]
}
GitHub Issue #5230 So, the reason for the error is the union type of CrudFilter, and the solution is to use a type guard like "field" in filter before accessing filter.field. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2h ago
<@236239059184386048> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?