The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

How to instanciate a file object in TypeScript

posted on 20.2.2023 by Below Surface in "TypeScript"

In our case we need to gather the information provided by a HTML form (text, date and file input), so they are available when the form is submitted.

One working way without TypeScript would be to have the following useState object:

const [uploadData, setUploadData] = useState({
        uploadTitle: "",
        uploadDate: "",
        uploadSubject: "",
        uploadFile: {}

But with TypeScript, this won't be allowed by the compiler. We need to instantiate the object the correct way, so it will be a file object. Thanks to StackOverflow, we know that that's the way to do it:

new File([""], "filename")

Whole useState code now:

const [uploadData, setUploadData] = useState({
        uploadTitle: "",
        uploadDate: "",
        uploadSubject: "",
        uploadFile: new File([""], "filename")

Change handlers of the inputs:

const changeHandler = (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLSelectElement>) => {
        setUploadData({...uploadData, []:})
const changeHandlerFile = (e: React.ChangeEvent<HTMLInputElement>) => {
        if ( == null) return;
        setUploadData({... uploadData, uploadFile:[0]});




More posts of this category

How to set a TypeScript type to an useState hook

Learn how to add a TypeScript type to React useState hooks


Find out the HTML input change event type in VS Code

An easy way to find out the correct input change event type for TypeScript