0
votes

Hello i'm trying to create an interface to get the following return in typescript:

  {
    "field": "departament_name",
    "errors": [
      "constraint": "O nome do departamento precisa ser do tipo String",
    ]   },

but I'm not getting it I'm getting the following error when I try to add the object to my array:

Type 'string []' is not assignable to type 'constraints []'. Type 'string' is not assignable to type 'constraints'.ts (2322)

interface:

export interface constraints {
  constraint: string
}
export interface errorFormater {
  field: string;
  errors: constraints[]
}

function:

export const formatErrors = (validationErrors: ValidationError[]): errorFormater[] => {
  let response: errorFormater[] = [];
  for (let error of validationErrors) {
    let field: string = error.property;
    let constraints: string[] = [];
    for (let constraint in error.constraints) {
      if (!error.constraints.hasOwnProperty(constraint)) {
        continue;
      }
      constraints.push(error.constraints[constraint]);
    };
    // console.log(property, errorMessage)
    response.push({ field, errors: constraints });
  }

  return response;
}
2
let constraints: string[] not the same as errors: constraints[] when you try push response.push({ field, errors: constraints });Nikita Madeev
if errors is an array of object, should contain braces {} else, : is not allowed in array of strings. is your sample data correct?Vaibhav

2 Answers

0
votes

The problem is that ValidationError.constraints type is not matching Constraint type. If ValidationError is your own type, you will have to either use the same Constraint type like this:

export interface IConstraint {
  constraint : string;
}
export interface IErrorFormater {
  field: string;;
  errors: IConstraint[];
}
export interface IValidationError {
  constraints : IConstraint[];
}

Or you could make a type cast (please don't..) https://techformist.com/type-casting-typescript/

0
votes

You should change your constraints varaible type from:

let constraints: string[] = [];

to:

let constraints: constraints[] = [];

And your response push to:

constraints.push({ constraint: error.constraints[constraint] });

This should work and you will get the response you want.

Cheers,