Switch the encoding format of a single property within the io-ts Codec.struct

Is there a way to change the Codec of a single property in an object without having to redefine everything else? For example, let's say I have a struct with a date field that sometimes receives input as a timestamp and other times as an ISO string depending on third-party API calls.

import * as COD from "io-ts/Codec";

const TimestampDateCodec: COD.Codec<unknown, number, Date> = {};
const IsoStringDateCodec: COD.Codec<unknown, string, Date> = {};

const current = COD.struct({
  id: COD.string,
  // a lot of other props...
  someDate: TimestampDateCodec, // I want to switch this to IsoStringDateCodec without redefining the whole struct
});


Answer №1

Unfortunately, it is not possible to achieve this task in that manner. The recommended approach is outlined below:

const base = {
  id: COD.string,
  // several other properties...
}

const OneVersion = COD.struct({
  ...base,
  someDate: TimestampDateCodec,
})

const AnotherVersion = COD.struct({
  ...base,
  someDate: IsoStringDateCodec,
})

Alternatively, you can use the following method:

const base = COD.struct({
  id: COD.string,
  // multiple other properties...
})

const OneVersion = COD.union([base, COD.struct({
  someDate: TimestampDateCodec,
})])

const AnotherVersion = COD.union([base, COD.struct({
  someDate: IsoStringDateCodec,
})])

The latter option may be more appealing if you prefer working with sum types. However, I find that the former results in a type that is easier to read in most Integrated Development Environments (IDEs). Personally, I have used the latter method before and ended up regretting it because my IDE displayed the time in a format like

{ ...base } & { ...someDate... } & ...
depending on how many unions were made.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you establish the default value for a form from an Observable?

Check out my TypeScript component below export interface Product{ id?:string, name:string, price:string; quantity:string; tags:Tags[]; description:string; files: File[]; } product$:Observable<Product | undefined>; ngOnIn ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Tips for utilizing automatic type detection in TypeScript when employing the '==' operator

When using '==' to compare a string and number for equality, const a = '1234'; const b = 1234; // The condition will always return 'false' due to the mismatched types of 'string' and 'number'. const c = a = ...

How do AppComponent and @Component relate to each other in AngularJs 2?

Recently, I came across the file app.component.ts in Example and found some interesting code. The link to the example is: here. Here's a snippet of the code: import { Component } from '@angular/core'; export class Hero { id: number; na ...

The type 'RefObject<HTMLDivElement>' cannot be matched with type 'RefObject<HTMLInputElement>' in this context

Encountered an error message: Issue with assigning types: Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement&g ...

A method for handling specific subsets of an enum in a secure and controlled manner

I have an enumerated type called Country and another type that represents a subset of European countries. I want to handle values within this subset differently from others. Currently, I am using an if statement with multiple conditions, but it could get u ...

Formatting Time in Angular 2 Using Typescript

Upon reviewing my date source, I found the following: TimeR ="2017-02-17 19:50:11 UTC"; Within the HTML file, I implemented this code snippet <span class="text-lg">{{TimeR | date: 'hh:mm'}}</span> The current output displays the t ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...

Utilizing functional components and formatter functionality in React with react-jsx-highcharts

Exploring the capabilities of react-jsx-highcharts through a polar chart. Software Versions: React: 17.0.1 react-jsx-highcharts: 4.2.0 typescript: 4.0.3 I opt for functional components in my code, hence no usage of "class" or "this." The snippet f ...

Issue with Displaying Local Server Image in Angular 2 HTML

I am facing an issue with my Angular 2 Application. It retrieves items from a local database where the server stores the image of the item and the database stores the path to that image stored on the server. While I can retrieve all the items without any p ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Launching ES Lint to handle SetStateAction within a TypeScript interface

Here is the component I have: import React, { SetStateAction } from 'react'; interface ColorObject { name: string, slug: string, hex: string, } interface Props { color: ColorObject onClick: React.Dispatch<SetStateAction<ColorObj ...

The class constructor in the TSdx package must be invoked with the 'new' keyword

I recently developed a npm package using TSdx to create a small Jest reporter. However, when I try to use this package in another project, an error occurs. Uncaught TypeError: Class constructor BaseReporter cannot be invoked without 'new' at ...

Tips for displaying three divs in one row and three divs in another row

I'm aiming for a design with 3 divs in one row and another 3 in the next, like this But what I currently have is different. Can someone assist me in achieving the desired layout? MY HTML : <div class="category-food"> < ...

Having trouble transferring information between two components in Angular version 14

Having recently delved into the world of Angular, I'm grappling with the challenge of passing data from a parent component to a child component. On my product listing page, clicking on a product should route to the product detail page, but I can' ...

The response from the Http GET request in the Angular web service app was delayed

I am currently working with Angular CLI version 8.3.2 and Node version 10.16.3 on win32 x64. My project involves integrating an Angular frontend with a .NET backend. The frontend communicates with the backend API to retrieve a list of messages using an HTT ...

Modifying the form-data key for file uploads in ng2-file-upload

I have implemented the following code for file upload in Angular 2+: upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a f ...

Expanding function parameter types using intersection type in Typescript

As I delve into the world of intersection types to enhance a function with an incomplete definition, I encountered an interesting scenario. Take a look at this code snippet: WebApp.connectHandlers.use("/route", (req:IncomingMessage, res:ServerResponse)=& ...

Avoid accessing invariant variables when mocking: __extends

I'm currently in the process of converting a collection of react components from JavaScript to TypeScript, and I've encountered an issue with jest.mock(). Before: "react": "^15.6.1" "jest": "20.0.4" "enzyme": "^2.9.1" CustomDate.js ... import ...

Determine rest parameters based on the initial argument

Struggling to generate a solution that infers the arguments for an ErrorMessage based on the provided code input. ./errorCodes.ts export enum ErrorCodes { ErrorCode1, ErrorCode2, ErrorCode3 } ./errorMessages.ts export const ErrorMessages = { [Err ...