TypeScript Type Transformation with Schema Encoding and Decoding

what is the correct way to do the following, I am trying to replace the original rarity object with a string and adding a color string. However, when encoding back, I merge these back into the rarity object. But TypeScript isn't sure that this reconstructed object matches the original A's rarity structure, especially if 'A' has more properties in rarity than just name and color, and surely the following is not correctly done, so what is the right way?
const transformRarity = <
  A extends {
    readonly rarity: {
      readonly color: string;
      readonly name: string;
    };
  },
  I,
  R
>(
  schema: S.Schema<A, I, R>
) => {

  const ast = schema.pipe(S.typeSchema, S.omit("rarity")).ast

  const Transformed = S.Struct({
    ...ast,
    rarity: S.String,
    color: S.String,
  });

  return S.transform(
    schema,
    Transformed,
    {
      decode: ({ rarity, ...data }) => ({
        ...data,
        rarity: rarity.name,
        color: rarity.color,
      }),
      encode: ({ rarity, color, ...rest }) => {
        const encoded: A = {
          ...rest,
          rarity: {
            name: rarity,
            color,
          },
        };
        return encoded;
      },
      strict: true,
    }
  ).pipe(S.asSchema);
};
Was this page helpful?