Typing issues when passing zod schema as function argument and using safeParse

23 views Asked by At

I'm trying to make a generic 'parse response' function in a database module designed for interacting with DynamoDB:

const parseDynamoResponse = <T extends z.ZodTypeAny>(items: Record<string, unknown>[] | undefined, schema: T) => {
    if (!items) return [];
    return items.map((item) => {
        const validatedItem = schema.safeParse(item);
        if (validatedItem.success) {
            return validatedItem.data as z.infer<T>;
        }
        logger().warn("item failed validation", validatedItem);
        return null;
    }).filter(isNotNullOrUndefined);
};

I'm trying to follow the implementation in the docs for using generic type arguments for schemas. However, even with the suggested typecasting for return validItem.data as z.infer<T>, TypeScript and ESLint are still not happy with that particular line:

ESLint: Unsafe return of type 'any' from function with return type 'TypeOf<T> | null'.(@typescript-eslint/no-unsafe-return

Can someone help me out with what I'm doing wrong here?

0

There are 0 answers