0

I'm trying to validate a form with react. Having main Controller, which has the model and handles the actual validation. Passing down model to child controllers, as well the validation errors.

How can i create an array which contains these errors, the array has a key which is a field name in the model, and value is the validation error message. I want to bind the models field names to the error message. Class for example what im looking for.

export class Model {
   SampleNumber: number;
   SampleString: string;
   Errors: [keyof Model, string];
}

Or is there a preferred way of handling validation messages in React with typescript.

1
  • Arrays don't have keys - you need to use an object for Errors if you want it to be contain key-value pairs. Commented Oct 29, 2018 at 11:13

1 Answer 1

1

Firstly, arrays don't have keys - you need to use an object for Errors if you want it to be contain key-value pairs.

If you want to specify the type of an object's keys, you'd use an index signature, like so:

export class Model {
    SampleNumber: number;
    SampleString: string;
    Errors: { [x: string]: string };
}

However, you can't currently use keyof Model alone in an index signature - you need to use a 'mapped type' instead, by specifying field in keyof Model. You can then combine this with the Partial mapped type to make it so not every field has to be present.

export class Model {
    SampleNumber: number;
    SampleString: string;
    Errors: Partial<{ [field in keyof Model]: string }>;
}

let model: Model = {
    SampleNumber: 1,
    SampleString: "",
    Errors: { SampleNumber: "error" }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.