I have this Attachment class that is supposed to be an extension of the js File type.
export interface Attachment extends File {
isVideo: boolean;
url: string;
}
export class Attachment implements File {
constructor(file: File) {
Object.assign(this, file);
this.isVideo = file.type.includes('/video');
this.url = URL.createObjectURL(file);
}
}
However, it seems that the Object.assign(this, file)
in the constructor doesn’t work because it is trying to assign to readonly properties of the default File type. This ends up getting me an object with only the "isVideo" and "url" props, which is not intended.
How can I work around that? Is there a better way to do it?
2
Answers
In TypeScript, it’s not possible to directly extend or subclass the File type because it’s a built-in type and its properties are read-only. However, you can create a wrapper class around the File object to achieve similar functionality.
Just create a class that
extends File
but if the
file
is already created outside, you should forget aboutextends
but store it as a property