Effect CommunityEC
Effect Community2y ago
2 replies
bsluther

TypeScript Schema Lookup and Decoding Challenge

Any ideas on how to look up a schema from a record by key, then decode an input conforming to the schema? The problem is that because each Schema is different, when I look up the schema by key TypeScript sees a union of all possible schemas, and I can't pass a value with that type into decodeUnknown.

Simplified example:

const schemas = {
  one: Schema.Struct({ name: Schema.String }),
  two: Schema.Number
} as const
type Schemas = typeof schemas

const namedDecode = <
  TName extends keyof Schemas,
  TFrom extends Schemas[TName]['Encoded'],
> (name: TName, input: TFrom) => {
  const schema = schemas[name]
  const decoder = Schema.decodeUnknown(schema)
  // Argument of type 'Struct<{ name: typeof String$; }> | typeof Number$' is not assignable to parameter of type 'Schema<{ readonly name: string; }, { readonly name: string; }, never>'.
  return decoder(input)
}

const resOne = namedDecode('one', { name: 'hello' })
// Effect.Effect<{ name: string }, ParseError, never>

const resTwo = namedDecode('two', 2)
// Effect.Effect<{ name: string }, ParseError, never>
Was this page helpful?