|
|
|
|
|
by jdthedisciple
1097 days ago
|
|
The code in question: (e: Event) => {
let t: EventTarget | null = e.target;
// here "t as HTMLInputElement" did not work
if (t instanceof HTMLInputElement && t.files && t.files[0]) {
const file = t.files[0];
if (file) {
(myImageElem! as HTMLImageElement).src = URL.createObjectURL(file);
}
}
}
TS wouldn't accept it. My guess is it's not cluttered enough.My final vanilla version OTOH: (e) => {
const t = e.target;
if (t.files) {
const file = t.files[0];
myImageElem.src = URL.createObjectURL(file);
}
}
How is the latter not a million times more elegant?
Why do I need to clutter everything with types that I won't even think twice about? |
|
`e` is inferred from `HTMLProps<HTMLInputElement>['onChange']`
`t` is inferred from `e`
`files` is inferred from `t`
No halfway experienced TS developer would write any of these annotations.
If you got the myImageElem from a ref, you may need to add a !, because yes, it's not technically guaranteed that the ref is set by the time the callback is called.