Search code examples
typescript

Require fields in FormData using TypeScript


I want to have FormData (documentation) interface with specified required fields. So I want to use TypeScript to check if my formData has all required fields.

export interface AddRequest {
  image: Blob;
  username: string;
}

// This is invalid
export interface AddRequestApi extends FormData {
  image: FormDataEntryValue;
  username: FormDataEntryValue;
}

so I can do:

export const mapRequest = (request: AddRequest): AddRequestApi => {
  const { image, username } = request;

  const formData = new FormData();
  formData.append('image', image);
  formData.append('username', username);

  // I want my ts compiler to check if returned formData has required fields
  // that should be stated in AddRequestApi type (or interface)
  return formData;
};

Solution

  • As @Fabian Lauer said:

    The approach of multiple .append() calls means the code can only be checked at runtime, not compile time (this means TS can't check it)

    Now, there are some ways runtime type-check can be achieved with TS.

    Check out this blog https://levelup.gitconnected.com/how-we-use-our-typescript-type-information-at-runtime-6e95b801cfeb

    Validation — using another equally as awesome tool, Another JSON Schema Validator or ajv, we can validate any object at runtime simply by passing in the object and our schema. We’ll even get error outputs in a format that we can use programmatically for things such as showing errors on a form against the field that is invalid, automatically fixing invalid properties, etc.