0

I am using io-ts to parse objects from JSON that can be any of a known variety of types. Each object comes in with a string key @type specifying what its type is. I would like to keep a Record/map of type names to io-ts type "class objects" so i can find the parsing class to use. This table needs to be the input to a function, and can be supplied by other libraries who consume this library. So I can't make assumptions about what sort of types are allowed, though I want to assume they will all have @type as a key.

but I am struggling to figure out how to specify what this table's type should be as a parameter. It seems to be something like "map of string to subclass of t.Type with at least the property @type." How would I specify that?

Example data:

[
  { "@type": "A",
    "a": "hello"
  },
  { "@type": "B",
    "b": "world"
  }
]

Code I am trying to write:

import * as t from 'io-ts';

export const A = t.type({
  '@type': t.literal('A'),
  a: t.string,
});

export const B = t.type({
  '@type': t.literal('B'),
  b: t.string,
});
// conceivably, any number of these may exist


export type TypesTable = Record<string, ???>

myParsingFunc(data: Data, table: TypesTable) {...}

One option I have been trying to get working is like this, but with the mystifying error showing up as commented:

export const SuperType = t.Type({
  '@type': t.string
})

export type TypesTable = Record<string, T extends SuperType> // E: '?' expected


// Another option that produces an error, but doesn't even express the right thing, because i don't want every entry in the table to refer to the same type:
export type TypesTable<T extends SuperType> = Record<string, T> // E: SuperType refers to a value, but is used as a type here

Any guidance in interpreting this error or how to represent subclasses in type signatures like this would be super appreciated!

qqq
  • 1,360
  • 1
  • 9
  • 24
  • The fundamentals of the error are that SuperType is a const not a type. You probably mean `T extends typeof SuperType` although I haven't examined the detail of what you're trying to do and I am not familiar with io-ts. – cefn Mar 07 '23 at 00:00

0 Answers0