I am working with an existing native type called File
, and I have a requirement to extend it by adding a field called id
. This is how my code currently looks:
type FileWithId = File & {
id: number;
};
const ATTACHMENTS = [
{
name: "some_file_name.txt",
...
},
{
name: "some_file_name2.txt",
...
}
];
const files = ATTACHMENTS.map((attachment) => {
const file: FileWithId = new File([], attachment.name);
file.id = attachment.id;
return file;
});
However, TypeScript is displaying an error message:
TS2322: Type 'File' is not assignable to type 'Attachment'.
Property 'id' is missing in type 'File' but required in type '{ id: number; }'.
If I remove the casting of type FileWithId
for file
, then the error becomes:
TS2339: Property 'id' does not exist on type 'File'.
Making the field id
optional resolves the issue at this point, but it leads to errors in other parts of my code. I want to highlight that id
is a required property in my type.
Casting the type like this:
const file = new File([], attachment.name) as FileWithId;
is not ideal for various reasons.
Is there a better way to solve this problem?