Custom Schema.TaggedClass with default _tag when using decodeUnknown
Is there a way to do this custom TaggedStruct from the docs but with Schema.TaggedClass?
import type { SchemaAST } from "effect"
import { Schema } from "effect"
const TaggedStruct = <
Tag extends SchemaAST.LiteralValue,
Fields extends Schema.Struct.Fields
>(
tag: Tag,
fields: Fields
) =>
Schema.Struct({
_tag: Schema.Literal(tag).pipe(
Schema.optional,
Schema.withDefaults({
constructor: () => tag, // Apply _tag during instance construction
decoding: () => tag // Apply _tag during decoding
})
),
...fields
})
const User = TaggedStruct("User", {
name: Schema.String,
age: Schema.Number
})
console.log(User.make({ name: "John", age: 44 }))
// Output: { _tag: 'User', name: 'John', age: 44 }
console.log(Schema.decodeUnknownSync(User)({ name: "John", age: 44 }))
// Output: { _tag: 'User', name: 'John', age: 44 }
import type { SchemaAST } from "effect"
import { Schema } from "effect"
const TaggedStruct = <
Tag extends SchemaAST.LiteralValue,
Fields extends Schema.Struct.Fields
>(
tag: Tag,
fields: Fields
) =>
Schema.Struct({
_tag: Schema.Literal(tag).pipe(
Schema.optional,
Schema.withDefaults({
constructor: () => tag, // Apply _tag during instance construction
decoding: () => tag // Apply _tag during decoding
})
),
...fields
})
const User = TaggedStruct("User", {
name: Schema.String,
age: Schema.Number
})
console.log(User.make({ name: "John", age: 44 }))
// Output: { _tag: 'User', name: 'John', age: 44 }
console.log(Schema.decodeUnknownSync(User)({ name: "John", age: 44 }))
// Output: { _tag: 'User', name: 'John', age: 44 }
