Typescript - ReactJS - Property 'directory' does not exist on type definition

Β·

1 min read

πŸ‡ Problem

When I try to upload a directory by using the input element with NextJS, ReactJS and TypeScript. A TypeScript error occurs:

Type '{ type: "file"; directory: string; multiple: true; webkitdirectory: string; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
Property 'directory' does not exist on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.ts(2322)

I think this is a weird error because the directory is a normal property in the HTML input element. πŸ₯²

I checked out the ReactJS type definition by using ctrl + click on the input element attribute name and found out that the directory property is not defined. πŸ₯²

🌾 The Solution

After some research, I found out that the directory property must be defined by using the following code. src/types/input-html.d.ts :

/* eslint-disable @typescript-eslint/naming-convention */
export {};

declare module 'react' {
  interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
    // extends React's HTMLAttributes
    directory?: string;
    webkitdirectory?: string;
  }
}

Now, the error is gone. ✨

We used the export {} line in our .d.ts file to mark it as an external module. directory and webkitdirectory are should be string type and optional properties.

🌱 Reference