fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
6.12k stars 195 forks source link

Type inference on findItem when using type predicates #867

Open cberthou opened 1 week ago

cberthou commented 1 week ago

For now, findItem returns the input type event when trying to narrow the typing using type predicates. For example :

import * as v from 'valibot';

type Animal = 'cat' | 'dog';

const isAnimal = (v: string): v is Animal => v === 'cat' || v === 'dog';

const schema = v.pipe(
  v.array(v.string()),
  v.findItem(isAnimal)
)

const animal = v.parse(schema, ['apple', 'cat', 'screw']);
// animal is type string | undefined

It would be cool to get better type narrowing. For now, you have to do this, which feels weird given that findItem exists :

const schema = v.pipe(
  v.array(v.string()),
  v.transform((array) => array.find(isAnimal)),
)
cberthou commented 1 week ago

I have a PR for this if you feel it can bring value to the project.

fabian-hiller commented 1 week ago

Thank you for creating this issue and your PR! I am very interested in improving it. I will try to have a closer look in about two weeks.