Effect CommunityEC
Effect Community3y ago
7 replies
Liam

Understanding the `optionFromNullable` Combinator in `@effect/schema`

Been loving @effect/schema so far, however I'm slightly confused by the input to the optionFromNullable combinator. The docs say that

The option combinator in @effect/schema/Schema allows you to specify that a field in a schema is of type Option<A> and can be parsed from a required nullable field A | undefined | null.

However, the following give me an error:

import * as S from "@effect/schema/Schema";

const schema = S.struct({
  nullableString: S.optionFromNullable(S.string),
})
interface From extends S.Schema.From<typeof schema> { }

declare const from: From;
from.nullableString
//  ^? string | null 
//  ^ doesn't include `undefined`

const parseUndefined = S.parseSync(schema)({
//    ^? { readonly nullableString: Option<string> }
//    ^ works when parsing
  nullableString: undefined
})

const decodeUndefined = S.decodeSync(schema)({
  nullableString: undefined
  // ^ error: "Type 'undefined' is not assignable to type 'string | null'.(2322)""
})

Here's the tsplay link https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&experimentalDecorators=true&emitDecoratorMetadata=true&exactOptionalPropertyTypes=true&noImplicitOverride=true&noPropertyAccessFromIndexSignature=true&noFallthroughCasesInSwitch=true&useUnknownInCatchVariables=true#code/JYWwDg9gTgLgBAKjgQwM5wMpwGZQiOAIgAEBTbbUgYxgHpUqALUkZWjJl5QgbgCg+VCADtU8Bs1ZwAvJgB0YqAFcaACgDefOHGFKANnuQAjPaQwwowYQHMAXPIhgYwEQDE8IAHL7DJ0qowFCytrAEoAGj4AX1C+KxhSKGxkKlI4d3w4UgAPBOEAE3RAjklkOQyQAB4YAE8wUghsOAkuAD44dTgogXzqQyg0oVF4XHx7Cv5RkDldA2NTc0sbPlpabQA9AH4Vtbh1uHyIUlRhAHJ4Kyo9JV64AAMlAvIrUny7gUERMTgwZChUUgAVSe2Be+Rk8l+-zMNWEVFULVYoQ0O20G22qzRezgAHdoABrdA45jCH5-VAhLQ6HzzMzBGz2R69UHCV7RWKfYYHagQXrA5lgiGBXpCXoYWHwxHIZGabSzXwLel2OBM56s-JUzH7RJ4KD2QgAFTqaVOqpZr1OcGA6GEEHgaAp1mEtLgMAgruNcFOihCcAAPtSDKc5KoAEwAZlDodChEI7KAA

I've made sure that strict and exactOptionalPropertyTypes are enabled.

tl;dr, is there a combinator to parse and decode A | undefined | null into Option<A>?
Was this page helpful?