Reputation: 1186
In my typescript project, I have a list of files coming from an input, I am trying run through a loop in typescript to check if there is any file exceeds the limit,
const allowSize = 104857600; // 100mb
const files = event.target.files;
const hasInValidFileSize = Array.from(files).filter(
(item) => allowSize < item.size // Error line
);
The functionality is working fine, but In console its giving me a build error.
TS2339: Property 'size' does not exist on type 'unknown'.
Please help me to fix
Upvotes: 0
Views: 4092
Reputation: 1186
I have resolved this issue by just adding (: any)
const files = event.target.files;
const hasInValidFileSize = Array.from(files).filter(
(item: any) => allowSize < item.size
);
`
Upvotes: 0
Reputation: 115
The event.target is unknown to Typescript, you should assign a type to it. I don't know the proper context of the code but something like this perhaps.
document.querySelector('#test')?.addEventListener('change', function(event) {
const allowSize = 104857600; // 100mb
const files = (<HTMLInputElement>event?.target)?.files;
if (!files) return;
const hasInValidFileSize = Array.from(files).filter(
(item) => allowSize < item.size // No more error
);
return hasInValidFileSize;
})
Notice the
(<HTMLInputElement>event?.target)?.files
Since files is a property of HTMLInputElement we can cast the event.target to this type and then request files on it, ? marks are potential undefined/empty values.
EDIT: It is not clear where your code resides thus Im offering a different style of writing to prevent JSX parsing the type declaration as an HTML element with a missing closing tag.
(event?.target as HTMLInputElement)?.files
Upvotes: 1