fastify-multipart
fastify-multipart copied to clipboard
Typescript data.fields returns wrong type.
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
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.
Would you like to send a Pull Request to address this issue? Remember to add unit tests.
OK. If I have enough time, I will give a try.
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.
Typescript have no way to know which is the suitable type for fields as it is mixed with both
file
andfield
.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.
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;
Any updates?
Any updates?
@gabrielrufino I haven't seen a PR from you yet.