티스토리 뷰

Property 'file' does not exist on type 'Multipart'. Property 'file' does not exist on type 'MultipartValue'.

 

@fastify/fastify-multipart 버전이 7.1.2 → 7.2.0 으로 바뀌면서 에러가 발생했다.

릴리즈 히스토리를 보니 Multipart type 이 바뀌게 되어서 발생하는듯 했고 아래와 같이 수정하여 해결했다.

 

1. Using type predicates

const isMultipartFile = (multipart: Multipart): multipart is MultipartFile => {
  return (
    (multipart as MultipartFile).file !== undefined &&
    (multipart as MultipartFile).toBuffer !== undefined
  );
};

for await (const part of parts) {
    if (isMultipartFile(part)) {
        // ...
    } else {
        // ...
    }
}

참조: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

 

Documentation - Advanced Types

Advanced concepts around types in TypeScript

www.typescriptlang.org

 

2. in operator

JS 를 사용한다면 기존의 코드로도 에러가 발생하지 않지만 TS 를 사용한다면 위의 예시처럼 수정하거나 if ('file' in part) 이런식으로 수정할 수도 있다.

fastify.post('/upload/raw/any', async function (req, reply) {
  const parts = req.parts()
  for await (const part of parts) {
    // if (part.file) {
    if ('file' in part) {
      await pump(part.file, fs.createWriteStream(part.filename))
    } else {
      console.log(part)
    }
  }
  reply.send()
})

 

 

비슷한 내용으로 다른 사람이 README 를 수정해야 한다고 코멘트를 달았는데 답변은.. 그렇다고 합니다...

Your problem is TypeScript issue.
TypeScript cannot restrict the type in certain format that's the cause.
The README example is certainly valid in Javascript.

 


https://github.com/fastify/fastify-multipart/pull/390

 

Improve typescript types by dwickern · Pull Request #390 · fastify/fastify-multipart

I've tried to correct the types by analyzing the source code and busboy's type definitions. Fixes #251 Checklist run npm run test and npm run benchmark tests and/or benchmarks are included docu...

github.com

 

'JavaScript & TypeScript' 카테고리의 다른 글

sharp image rotate 문제  (0) 2023.03.12
JS RegExp perfomance  (0) 2022.09.24
브라우저, JS 흐름 정리 메모  (2) 2022.05.22
Udemy 클린코드 JS 강의 정리  (1) 2022.01.06
Next export 시 Image Optimization 설정 문제  (3) 2022.01.03