fabian-hiller / valibot

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

Type inference on findItem when using type predicates #867

Closed cberthou closed 2 weeks ago

cberthou commented 1 month 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 month ago

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

fabian-hiller commented 1 month 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.

fabian-hiller commented 2 weeks ago

This is now implemented and will be available with the next version. Thank you for your feedback!

fabian-hiller commented 2 weeks ago

v1.0.0-beta.4 is available