typescript default function inside interface

Viewed 35320

This is working

interface test{
    imp():number;
}

but it is possible to implement a function inside.

interface test{
    imp():number{
      // do something if it is not overwritten
    }
}

This is not working in typescript for me, but there may be some reserved word, for example default or similar, to implement a function inside an interface that is not overwritten if the default work.

3 Answers

Your needs will be fulfilled by abstract classes

abstract class Department {

    constructor(public name: string) {
    }

    printName(): void {
        console.log("Department name: " + this.name);
    }

    abstract printMeeting(): void; // must be implemented in derived classes
}

class AccountingDepartment extends Department {

    constructor() {
        super("Accounting and Auditing"); // constructors in derived classes must call super()
    }

    printMeeting(): void {
        console.log("The Accounting Department meets each Monday at 10am.");
    }

    generateReports(): void {
        console.log("Generating accounting reports...");
    }
}

Credits https://www.typescriptlang.org/docs/handbook/classes.html#:~:text=Abstract%20classes%20are%20base%20classes,methods%20within%20an%20abstract%20class.

For more info https://www.typescriptlang.org/docs/handbook/classes.html#:~:text=Abstract%20classes%20are%20base%20classes,methods%20within%20an%20abstract%20class.

I've discovered that Typescript seems to allow an interface and another class or object to share the same name. So you can do this:

interface test {
    imp(): number
}

class test {
    static imp() { return 123 }
}

class test2 /* extends something */ implements test {
    imp() { return test.imp() }
}

It's a pity TS doesn't support function implementations in interfaces, like Kotlin does, to save us writing the wrapper methods, because it could be implemented quite easily in the underlying Javascript.

Related