fastify-multipart icon indicating copy to clipboard operation
fastify-multipart copied to clipboard

Typescript data.fields returns wrong type.

Open abcfy2 opened this issue 3 years ago • 7 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure it has not already been reported

Fastify version

3.8.1

Plugin version

4.0.7

Node.js version

14.17.1

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Manjaro 21

Description

Seems that the type define of fields is not correct.

export type Multipart<T = true> = T extends true ? MultipartFile : MultipartValue<T>;

Seems this make Multipart type is always MultipartFile, never MultipartValue.

Steps to Reproduce

image image

image

Building error:

TS2339: Property 'value' does not exist on type 'MultipartFile | MultipartFile[]'.
  Property 'value' does not exist on type 'MultipartFile'.

Expected Behavior

data.fields.{field_name} should able to return MultipartValue type.

abcfy2 avatar Jul 01 '21 13:07 abcfy2

Would you like to send a Pull Request to address this issue? Remember to add unit tests.

mcollina avatar Jul 01 '21 22:07 mcollina

OK. If I have enough time, I will give a try.

abcfy2 avatar Jul 02 '21 02:07 abcfy2

Typescript have no way to know which is the suitable type for fields as it is mixed with both file and field.

One of the usage is type augmentation if you have only single endpoint for file handling.

declare module 'fastify-multipart' {
  interface MultipartFields {
    foo: MultipartValue<T>
    file: MultipartFile
  }
}

Other way is type casting.

climba03003 avatar Jul 02 '21 02:07 climba03003

Typescript have no way to know which is the suitable type for fields as it is mixed with both file and field.

One of the usage is type augmentation if you have only single endpoint for file handling.

declare module 'fastify-multipart' {
  interface MultipartFields {
    foo: MultipartValue<T>
    file: MultipartFile
  }
}

Other way is type casting.

I have sort of the same issue. But redeclaration specifically for the file property doesn't work. TS keep reading module's typings.

The only solution was using type casting as you suggested.

sanzhardanybayev avatar Sep 22 '21 03:09 sanzhardanybayev

For anyone wondering what to do in the case of a single file upload with extra fields

type BodyFields = {
  foo: string
  bar: string
}

const data = await req.file();
const file = await data.toBuffer();
const fields = data.fields as any as {
    [key in keyof BodyFields]: {
        value: BodyFields[key];
    };
};
const foo = fields.foo.value;
const bar = fields.bar.value;

realfresh avatar Feb 10 '22 01:02 realfresh

Any updates?

gabrielrufino avatar Feb 11 '22 17:02 gabrielrufino

Any updates?

@gabrielrufino I haven't seen a PR from you yet.

mcollina avatar Feb 11 '22 19:02 mcollina