const files = ref<File | null>(null)
console.log('event.target.files ::: ', event.target.files)
files.value = event.target?.files
console.log('files ::: ', files)
<input type="file"> 로 파일 업로드를 하고 이것을 event.target.files 로 찍어보면 아래처럼 나온다.
(타입 에러때문에 유튜브를 뒤지다가 const files = ref<File | null>(null) 이렇게 하신 분을 봐서 에러가 안나는 것까지는 확인했는데 아직 왜 저렇게 해야만 에러가 안나는지 이해는 못하는중.. 아시는 분 있으시면 댓글 부탁드려요 ㅠ^ㅠ)
저 FileList는 index가 있어서 배열처럼 보이지만 사실은 유사배열객체이다. 일반 객체는 length가 존재하지 않는다!
유사배열객체이기 때문에 배열의 메소드를 사용할 수 없다.
console.log('files ::: ', files[0])
배열처럼 files[0]으로 접근한다면?
Element implicitly has an 'any' type because expression of type '0' can't be used to index type
과 같은 에러가 나온다. (콘솔은 잘 찍히지만 빨간줄이 그어져있다..) 타입스크립트는 저 0을 숫자로 받아들이기 때문에 인덱스로 인식하지 못해서 나는 에러라고한다. (잘 이해가 안돼서 지피티한테 물어봤다)
이것을 해결하려면 배열로 바꿔주면 되는데 Array.from 을 많이 쓰는 것 같아서 써봤다.
No overload matches this call.
Overload 1 of 4, '(iterable: Iterable<File> | ArrayLike<File>): File[]', gave the following error.
Argument of type '{ readonly lastModified: number; readonly name: string; readonly webkitRelativePath: string; readonly size: number; readonly type: string; arrayBuffer: () => Promise<ArrayBuffer>; slice: (start?: number | undefined, end?: number | undefined, contentType?: string | undefined) => Blob; stream: () => ReadableStream<......' is not assignable to parameter of type 'Iterable<File> | ArrayLike<File>'.
Type 'null' is not assignable to type 'Iterable<File> | ArrayLike<File>'.
Overload 2 of 4, '(arrayLike: ArrayLike<File>): File[]', gave the following error.
Argument of type '{ readonly lastModified: number; readonly name: string; readonly webkitRelativePath: string; readonly size: number; readonly type: string; arrayBuffer: () => Promise<ArrayBuffer>; slice: (start?: number | undefined, end?: number | undefined, contentType?: string | undefined) => Blob; stream: () => ReadableStream<......' is not assignable to parameter of type 'ArrayLike<File>'.
Type 'null' is not assignable to type 'ArrayLike<File>'.
Array.from의 인자값이 안맞다고 한다!
유사배열객체를 받는다고 했는데... 왜 이런 에러가 나는지는 모르겠다. ㅠㅠ
Array.prototype.slice() 도 비슷하게 배열로 바꿔주는데 얕은 복사본을 새로운 배열 객체로 반환한다고 한다.
(출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
Array.prototype.slice()로 배열 변환을 했더니 성공했다. 타입스크립트 얼레벌레 보고 빠르게 하는 중이라 왜인지는 잘 모르겠지만 일단 배열로 바꿔졌으니 포스팅해본다 ㅜ.. 타입스크립트 정말 어렵네