rescript-schema icon indicating copy to clipboard operation
rescript-schema copied to clipboard

Questions around null and undefined

Open chenglou opened this issue 10 months ago • 2 comments

  1. nullish seems less usable than imagined

    const aSchema = S.nullish(S.number)
    type AType = S.Output<typeof aSchema> // number | undefined
    const a: AType = null
    // ^ Type 'null' is not assignable to type 'number | undefined'
    

    I get that we try to conveniently convert inbound data from null to undefined, but after a few indirection layers it turns out not as convenient as it seems. For example if you try to test things, try to use the same helper codepath and insert your own data that contains explicit null, etc. Then you end up turning that schema into S.union([S.number, null, undefined]) anyway.

  2. there's S.undefined but not S.null

  3. nullable is kind of a misleading name for TS users

it seems to me that all these overly detailed nuances can be ejected to user land if the project recommended S.union([mySchema, null]), S.union([mySchema, null, undefined]) etc. And if that's too long, convenience helpers that directly map to the names, e.g. S.nullUndefined(mySchema). If it's less idiomatic ReScript then these can just stay as aliases purely in the TS implementation. No strong opinion on adding these though; just a thought. I like that the library's lean

chenglou avatar Feb 26 '25 00:02 chenglou

  1. Yeah, the reasoning behind it was that it's convenient in ReScript, but I agree with you that for TS it's better to keep the type as it is. I'm currently working on a fix in v10 branch

  2. Oh, S.undefined is a legacy. It should be removed in favor of S.schema(undefined)

  3. I took the naming from Zod https://github.com/colinhacks/zod#nullish I Agree about it being weird, but I'd like to keep the helpers around. Also, they are needed to handle S.nullish(S.nullable(S.string)) nicely in regards of resulting schema

DZakh avatar Feb 26 '25 06:02 DZakh

I'll keep the current API and stop transforming null to undefined.

DZakh avatar Feb 26 '25 06:02 DZakh