Back

Technologies:

javascriptjavascript
reactjsreactjs
typescripttypescript
avatar
Tolerim
a month ago

How can I determine the data type of elements?

I require assistance with an issue I am experiencing.

Please refer to the attached image here.

To provide some context, I have written the following code:

<ButtonWrapperStyled>
    <input {...getInputProps()} />
    <Button {...getRootProps()}>Загрузить</Button>

    {files.map((file) => {
        if (file instanceof File || file.constructor.name === "FileProps") {
            return <div>{file.fileId}</div>
        } else {
            return <div>{file.fileId}</div>
        }
    })}
</ButtonWrapperStyled>
My question is: how can I correctly check the type of the "file" variable in this instance?

I have attempted to console log the "file" variable to no avail, and I am unable to resolve the issue myself.

Answers(2)
avatar
Vogi
a month ago
Verified Answer
To check the type of a variable in JavaScript, you can use the typeof operator. The typeof operator takes a variable and returns its type in a string format. In your code snippet, you can check the type of the "file" variable by using the typeof operator as follows:
if (typeof file === 'object' && file instanceof File) {
    console.log('file is an instance of File');
} else {
    console.log('file is not an instance of File');
}
The above code checks if the "file" variable is an instance of the File object. I hope this helps! Let me know if you have any other questions.

Sources

How to check the type of a variable or object in JavaScriptJavaScript Type Checking – How to Check Type in JS with typeof()How to return the data type of variable in JavaScript - GeeksForGeeksJavaScript TypeOf – How to Check the Type of a Variable or Object in JSFinding Variable Type in JavaScript - Stack OverflowJavaScript typeof - W3School
avatar
Tolerim
a month ago
You can check the type of file using the instanceof operator. Here's an example of how you can use it in your code:
{files.map((file) => {
    if (file instanceof FileProps) {
        return <div>{file.fileId}</div>
    } else if (file instanceof File) {
        return <div>{file.name}</div>
    } else {
        return null;
    }
})}
In this example, we are checking whether the file is an instance of FileProps or File. If it is an instance of FileProps, we display the fileId property of the object. If it is an instance of File, we display the name property of the object. If it is neither of these types, we return null.
;