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, [e.target.name]: e.target.value})
}
    
const changeHandlerFile = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files == null) return;
        setUploadData({... uploadData, uploadFile: e.target.files[0]});
};

Tags:

typescript
react
usestate
instanciation

Sources:

https://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript

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

TypeScript

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

TypeScript