DEV Community

Discussion on: My confusions about TypeScript

Collapse
 
coly010 profile image
Colum Ferry • Edited

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());
Collapse
 
kenbellows profile image
Ken Bellows

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.