skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Just create a class that extends File

    export class Attachment extends File {
        get isVideo() {
            return this.type.includes('/video');
        }
        getURL() {
            return URL.createObjectURL(this);
        }
    }
    
    // the constructor arguments is the same to "File"
    const attachment = new Attachment([], "filename.txt");
    

    but if the file is already created outside, you should forget about extends but store it as a property

    export class Attachment2 {
        constructor(public file: File) { }
        get isVideo() {
            return this.file.type.includes('/video');
        }
        getURL() {
            return URL.createObjectURL(this.file);
        }
    }
    
    const attachment = new Attachment(THE_FILE);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search