Skip to content

Record keys are not transformed #1252

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
siikasmaa opened this issue May 15, 2025 · 1 comment
Closed

Record keys are not transformed #1252

siikasmaa opened this issue May 15, 2025 · 1 comment

Comments

@siikasmaa
Copy link

Hey there,

I have the assumption that Record type keys could be transformed e.g. the following way:

const A = Type.Transform(Type.String())
  .Decode(value => `key-${value}`)
  .Encode(value => value)

const B = Type.Number()

const C = Type.Record(A, B)

const result = Value.Parse(C, {
  '1': 1,
  '2': 2
})

The result is { '1': 1, '2': 2 } while my expectation is that it would be { 'key-1': 1, 'key-2': 2 }. The static type of result is never as there is no guard within Record which would check for Transform. Is this something that could be added? Interested to hear your thoughts before trying to add it myself.

@sinclairzx81
Copy link
Owner

@siikasmaa Hi, sorry for the delay

I have the assumption that Record type keys could be transformed e.g. the following way:

This is a general limitation with Transforms. As of the current version, Transform types cannot be used to transform Record keys, but do agree this feature would be ideal. The way to approach this is to wrap the Record in a exterior transform.

const T = Type.Transform(Type.Record(Type.String(), Type.Number()))
  .Decode(value => Object.keys(value).reduce((result, key) => {
      return { ...result, [`key-${key}`]: value[key] }
    }, {}) as Record<`key-${string}`, number>)
    .Encode(value => value)

const result = Value.Parse(T, { '1': 1, '2': 2 })

console.log({ result }) // { result: { 'key-1': 1, 'key-2': 2 } }

I am investigating ways to improve Key transformation in the next revision, but for now, the above is the way to approach things.

Will close up this issue for now, but happy to field any additional questions on this thread.
Cheers
S

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants