loading...

re: My confusions about TypeScript VIEW POST

FULL DISCUSSION
 

This works, but it's rather annoying to have to reinvent the wheel this way

Interfaces are not for reinventing the wheel.
Your interfaces should be defined first and should contain the minimum common behaviour between similar objects that will implement them.

Think of an interface as a contract that needs to be fulfilled by the classes that implement it.

This means any method that only needs to use a specific behaviour that multiple objects contain, only needs to accept any object that implements it.

interface IExecutable {
    execute(): void;
}

class LogExecuter implements IExecutable {

    output: string;

    addOuput(log: string) {
        this.output += log;
    }

    execute(){
        console.log(this.output);
    }

}


class FileExecutable implements IExecutable {

    writeToFile() {
       // Do file ops
    }

    execute() {
        this.writeToFile();
    }


}

myMethod(executable: IExecutable) {
    executable.execute();
}

// Now we can call myMethod with either of the two classes above

myMethod(new LogExecuter());
 

The point is that the base classes are already defined in the library I'm using, and I was only using the interface as a hack to be able to pass around the classes in the way I needed to. I understand the purpose and usefulness of interfaces as a construct, but that wasn't my situation.

Code of Conduct Report abuse