Class-transformer: plainToClass : Type 'XX[]' is not assignable to type 'XX'

Created on 9 Nov 2016  路  6Comments  路  Source: typestack/class-transformer

Using webpack and angular2 + Webstorm, I've got an error ...

These 2 methods have the same name but one is for array..

export declare function plainToClass2>(cls: ClassType, plain: V, options?: ClassTransformOptions): T[];
export declare function plainToClass(cls: ClassType, plain: V, options?: ClassTransformOptions): T;

I have a class XX in TypeScript

private _myVar : XX;
....
this._myVar = plainToClass(XX, obj['xx'])

Webstorm shows it in red..... and webpack doesn't want to compile...

I have to rename this function so that it works (I don't use arrays).
export declare function plainToClass2>(cls: ClassType, plain: V, options?: ClassTransformOptions): T[];

thank you for your help

donreleased fix

Most helpful comment

Usage example:

let user: User = plainToClass<User, Object>(User, json);

All 6 comments

Usage example:

let user: User = plainToClass<User, Object>(User, json);

Thanks for the answer. This should be added to the docs.

Sometimes you have to do this instead:

  const app: BusinessApplication = plainToClass(BusinessApplication, req.body as Object);

thanks @devpreview, that was painful

This has been fixed. Currently not reproducible with 0.3.1. Minimal example:

import 'reflect-metadata';
import { plainToClass, Expose, Exclude } from 'class-transformer';

@Exclude()
class Example {
  @Expose()
  name: string;

  constructor(name: string) {
    this.name = name;
  }
}

const nameA = new Example('A');
const nameB = new Example('B');

const result = plainToClass(Example, [nameA, nameB]);
// result has the proper type: Example[]

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings