The function plainToClass does not transform a Date object into a string

Based on the information provided in the documentation, it is recommended that a Date object be converted to a string:

It's important to note that dates will automatically be converted to strings when attempting to convert a class object to a plain object.

However, my code example using class-transformer version 0.2.3 is not behaving as expected:

class TestDate {
  @Type(() => Date)
  aDate!: Date;
}

const testDate = new TestDate();
testDate.aDate = new Date();

const result: any = classToPlain(testDate);
console.log(typeof result.aDate);

When running this code, the console output shows object instead of the expected string. Have I overlooked something?

Answer №1

To elaborate on the solution provided by TmTron, I had to develop two transformers - one for each direction. These were then merged into a single decorator using this particular method:

// TransformDate.ts
import { Transform } from "class-transformer";

export default function TransformDate() {
  const toPlain = Transform((value) => (value as Date).toISOString(), {
    toPlainOnly: true,
  });

  const toClass = Transform((value) => new Date(value), {
    toClassOnly: true,
  });

  return function (target: any, key: string) {
    toPlain(target, key);
    toClass(target, key);
  };
}

Example of Usage:

// User.ts
import TransformDate from './TransformDate';

export default class User {
  id: string;
  @TransformDate()
  createdDate: Date;
  // ...
}

Answer №2

The documentation contains an error in the following sentence (refer to class-transformer#326):

It should be noted that dates will be converted to strings when attempting to convert a class object to a plain object.

To resolve this issue, you can use @Transform:

  @Transform(value => (value as Date).toISOString(), {
    toPlainOnly: true
  })

Check out the Codesandbox example with workaround

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

Variable type linked to interface content type

Is it possible to link two fields of an interface together? I have the following interface: export interface IContractKpi { type: 'shipmentVolumes' | 'transitTime' | 'invoices'; visible: boolean; content: IKpiContent; } ...

What is the functionality of mergeMap in handling errors?

In our unique scenario, we are dealing with a specific use case where we need to load 200 images 10 at a time. Utilizing MergeMap with concurrency in rxjs seems like the ideal approach for handling 200 HTTP requests and executing them in batches of 10. How ...

Maintaining the generic types in mapped types in TypeScript

In my current project, I have a unique design where a class contains instance methods that act as handlers, each representing a specific operation. These handlers take a reference as input and assign the output to a second parameter. To simplify this proce ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

Utilizing Typescript to define key-value pairs within a structured form

I've been creating a form structure that's functioning smoothly, but I've encountered an interesting issue with field validation in the validation part. While my Visual Code is pointing out that 'required2' in the phone constant n ...

Ionic is throwing a reference error stating that __importDefault is not defined

My project is encountering the following error when I try to run it: Uncaught ReferenceError: __importDefault is not defined at Module../src/app/app.component.ts (app.component.ts:9) at __webpack_require__ (bootstrap:84) at Module../src/app/app.module.ts ...

Handling functions in Ant Design Select component with TypeScript types

I have a query. Antd offers a custom Select input with functions like onSelect, onChange, etc. I am utilizing the onSelect function which requires the following arguments: (JSX attribute) onSelect?: ((value: string | number | LabeledValue, option: OptionDa ...

Working with Yarn and Webpack: Incorporating a TypeScript .ts file from an external Node directory not controlled by Yarn/Webpack

I am currently working on a k6 project for load testing, utilizing Yarn and Webpack. This project is stored within a sub-folder of a larger repository that primarily uses npm Node modules. My goal is to access a secret from AWS's Secrets Manager in t ...

Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area. I am curious about dynamically adding a getter method to a Prototy ...

Compiled TypeScript files are missing require statements for imported components

Recently delved into Angular 2 and encountered an unusual issue. I kicked off using the Angular 2 Quickstart repository on GitHub and incorporated some components with templates. For example: import { Component } from '@angular/core'; import { ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

How to simulate a typescript class using vitest

I am encountering a situation where I have a class A that imports another class B from a separate module and creates an instance of it. While writing tests for class A, I want to stub or mock some of the methods of class B. Below is an example code snippe ...

Building a versatile component library for Next.js using TypeScript and Tailwind CSS: Step-by-step guide

Lately, I've been utilizing Next.js and crafting components such as buttons, inputs, and cards with Tailwind CSS for my various projects. However, the repetitive task of rewriting these components from scratch for each new project has become quite tir ...

Ways to retrieve the "this" keyword in a <script setup> Vue Single File Component

Currently, I am developing a basic scaffold for vite, vue, and vuetify utilizing typescript. My goal is to implement the script setup version of SFC Vue. <script setup lang="ts"> One particular challenge I am facing is how to access proper ...

Angular TypeScript test checking file size with Jasmine

Seeking optimal method for testing File size during input type="file" change event. Currently, my test specification appears as follows: it('attach file with too large size', () => { const file: File = { name: 'filename', ...

Array still has elements, but the browser console is displaying a length of 0 [React TypeScript - API request]

When working inside a React component, I've created a function that gets triggered once the component is rendered: function getGlassesNames () { let outputArray:string[] = getGlassesOriginal(); console.log(outputArray); console.log(typeof ...

Is it necessary to manually validate parameters in TypeScript when developing a library?

Understanding the basic workings of TypeScript, it's clear that TypeScript transpiles code to JavaScript without adding extra behavior like type checking during execution. For instance, function example(parameter: string): void { console.log(paramet ...

Looking up the Vue.js type definitions in TypeScript

I'm currently working on enabling type checking in my Vue.js code (v2.2.1). My initial goal is to ensure that this specific line compiles with TypeScript (meaning I want the Vue class to be properly identified): var app = new Vue(); I've discov ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

The browser has overridden the content length

While attempting to upload a file through a put call, I encountered an issue with the Content Range not matching the total number of bytes specified by the API. When I tried to manually set the content length, I received an error stating "Refused to set un ...