I'm trying to define a new codec with io-ts
.
The shape should look like the following when I'm done:
type General = unknown;
type SupportedEnv = 'required' | 'optional'
type Supported = {
required: General;
optional?: General;
}
(Note: for the time being the shape of General
is not important)
The key here is that I want to derive the type based on General
and SupportedEnv
.
Currently, I have something like:
const GeneralCodec = iots.unknown;
const SupportedEnvCodec = iots.union([
iots.literal('required'),
iots.literal('optional'),
]);
const SupportedCodec = iots.record(SupportedEnvCodec, GeneralCodec)
type Supported = iots.TypeOf<typeof SupportedCodec>;
The type Supported
has both keys required:
type Supported = {
required: General;
optional: General;
}
How can I make it so that optional
is indeed optional?
I've tried using an intersection and partial... but I can't figure out the syntax with iots.record
.
Is this possible? Do I need to think about this differently?
Update
Creating a mapping function
partialRecord
(leveragingio-ts
's peer dep onfp-ts
), we can get to where we wanted all along.This yields the desired type:
Original Answer
The closest I've gotten is to add one extra level of indirection, which is unfortunate.
For example:
This produces the type:
Which... is close - though I really wish I didn't need that extra level, but it does answer my original question in a roundabout way.