gcanti / io-ts

Runtime type system for IO decoding/encoding
https://gcanti.github.io/io-ts/
MIT License
6.68k stars 331 forks source link

Clarification question - how to work with the type of codecs themselves? #689

Closed ships closed 1 year ago

ships commented 1 year ago

📖 Documentation

I have been searching the documentation but not found yet a clear answer as to how Codecs should be treated themselves in the type system. How would I specify that my function wants an argument whose type is "collection/array/record of io-ts codecs"? More challenging (to my brain), "array of io-ts codecs that intersect with a given io-ts codec [or at least that represent values whose types match some interface]"?

I may just be getting confused about the use of classes in typescript vs types for generic constraints. But I have tried every version of Record<string, myIoTsType> i can think of and get errors every way; i have bottomed out with typeof myIoTsType which is just Object.

Example/use case:

export const myIoTsType = t.type({
  '@type': t.string,
});
// would like to specify subclasses/extenders of myIoTsType elsewhere
const typeA = t.type({
  '@type': "A",
  a: t.string,
})
const typeB = t.type({
  '@type': "B",
  b: t.string,
})

{  // what is the right way to express the type of this object relative to `myIoTsType` so that it can be passed as an argument?
  "A": typeA,
  "B": typeB,
}

I am working on a Typescript project in which I need to decode structured objects from an intermediate representation (can pretend it's JSON for io-ts purposes) where those objects contain an identifier like @type. The consumer of my function/library wants to pass in the data, as well as a lookup table that maps from the string values found in @type field to the right io-ts codec to use for decoding.

Thank you! I am happy to add this documentation once I understand how it should be done.

ships commented 1 year ago

I see that in the codebase of io-ts-types this is dealt with by <C extends t.Mixed>. That has worked so far in my use cases.