No. Interfaces don't exist at runtime, so there's no way to add runtime code such as a method implementation. If you post more specifics about your use case, a more specific or helpful answer may be possible.

EDIT:

Ah, you want multiple inheritance which you can't do with classes in JavaScript. The solution you are probably looking for is mixins.

Adapting the example from the handbook:

class A {
    somePropertyA: number;
    someFunctionA() {
        console.log(this.somePropertyA);
    }

}

class B {
    somePropertyB: string;
    someFunctionB() {
      console.log(this.somePropertyB);
    }

}

interface C extends A, B {}
class C { 
    // initialize properties we care about
    somePropertyA: number = 0;
    somePropertyB: string = 'a';   
}
applyMixins(C, [A, B]);

const c = new C();
c.someFunctionA(); // works
c.someFunctionB(); // works        

// keep this in a library somewhere    
function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

That should work for you. Maybe eventually this can be done less painfully with decorators, but for now the above or something like it is probably your best bet.

Answer from jcalz on Stack Overflow
Discussions

Replacing Inheritance with default interface implementation
Definitely worth something! In fact, if I understand your idea correctly, Kotlin already did it . If a class Xyz has a field b: Base which implements some interface MyInterface, then Xyz can implement the same interface via class Xyz(val b: Base): MyInterface by b { // ... class body } And you can override any interface methods you want in the class using the usual override keyword, just like normal. (Technically, b needn't even be a field; merely a constructor argument, which is useful if all you need it for is the interface implementation) More on reddit.com
🌐 r/ProgrammingLanguages
31
12
July 10, 2024
Interface Default Values
Suggestion This will be a very useful feature If we could provide default values for interfaces , In Kotlin you can already do this using interface Y { val x : Int get() = 5 } There's a stackov... More on github.com
🌐 github.com
3
July 12, 2023
Typescript interface default values - Stack Overflow
Default values to an interface are not possible because interfaces only exists at compile time. You could use a factory method for this which returns an object which implements the XI interface. More on stackoverflow.com
🌐 stackoverflow.com
Defaulting Unspecified Interface Properties to Null in TypeScript - Ask a Question - TestMu AI Community
I have the following TypeScript interface: interface IX { a: string; b: any; c: AnotherType; } I declare a variable of this type and initialize all the properties with default values: let x: IX = { a: … More on community.testmuai.com
🌐 community.testmuai.com
0
July 25, 2024
🌐
GitHub
github.com › microsoft › TypeScript › issues › 3536
Allow default methods/instance variables in interfaces · Issue #3536 · microsoft/TypeScript
June 17, 2015 - interface IFoo { bar = true; } class Foo {} class Bar implements IFoo {} new Foo().bar; // undefined new Bar().bar; // true ... Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.This issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScriptAn idea for TypeScript
Author   dead-claudia
🌐
DEV Community
dev.to › qpwo › documenting-default-interface-values-in-typescript-or-trying-to-3b01
Documenting default interface values in typescript, or trying to... - DEV Community
May 9, 2022 - Surely the declaration file will point your numerous future library users to this class, and if they examine it with a careful eye, they will be able to determine the default values of your optional arguments. You hold your breath, run tsc, and open index.d.ts · interface PartialOptions { id: string excellence: number color?: string isAdmin?: boolean } export declare function addUser(options: PartialOptions): void export {}
🌐
Reddit
reddit.com › r/programminglanguages › replacing inheritance with default interface implementation
r/ProgrammingLanguages on Reddit: Replacing Inheritance with default interface implementation
July 10, 2024 -

I have been thinking about inheritance vs composition a bit lately. A key point of inheritance is implicit reuse.

Lets say we want to extend the behavior of a function on a class A. In a language with inheritance, it is trivial.

class A {
  func doSomething() { }
}

class Ae extends A {
  func doSomething() {
    super.doSomething();
    // we do something else here
  }
}

With composition and an interface we, embed A within Ae and call the method and, within expectation, have the same result

interface I {
  func doSomething();
}

class A implements I {
  func doSomething() { }
}

class Ae implements I {
  A a;
  func doSomething() {
    a.doSomething();
    // do someting else
  }
}

This works great... until we run into issues where the interface I is long and in order to implement it while only modifying one method, we need to write boiler plate in Ae, calling A as we go explicitly. Inheritance eliminates the additional boiler plate (there may be other headaches including private data fields and methods, etc, but lets assume the extension does not need access to that).

Idea: In order to eliminate the need to explicit inheritance, we add language level support for delegates for interfaces.

interface I {
  func doSomething();
  func doSomething2();
}

class A implements I {
  func doSomething() { }
  func doSomething2() { }
}
// All methods in I which are not declared in Ae are then delegated to the
// variable a of type A which implements I. 
class Ae implements I(A a) {
  func doSomething() {
    a.doSomething();
    // do someting else
  }
  // doSomething2 already handled.
}

We achieve the reuse of inheritance without an inheritance hierarchy and implicit composition.

But this is just inheritance?

Its not though. You are only allowed to use as a type an interface or a class, but not subclass from another class. You could chain together composition where a "BASE" class A implements I. Then is modifed by utilizing A as the default implementation for class B for I. Then use class B as default implementation for class C, etc. But the type would be restricted into Interface I, and not any of the "SUB CLASSES". class B is not a type of A nor is class C a type of B or A. They all are only implementing I.

Question:

Is this worth anything or just another shower thought? I am currently working out ideas on how to minimize the use of inheritance over composition without giving up the power that comes from inheritance.

On the side where you need to now forward declare the type as an interface and then write a class against it, there may be an easy way to declare that an interface should be generated from a class, which then can be implemented like any other interface as a language feature. This would add additional features closer to inheritance without inheritance.

Why am I against inheritance?

Inheritance can be difficult? Interfaces are cleaner and easier to use at the expense of more code? Its better to write against an Interface than a Class?

Edit 1:

Both-Personality7664 asked regarding how internal function dependencies within the composed object would be handled.

A possible solution would be how the underlying dispatching works. With a virtual table implementation, the context being handled with the delegate would use a patched virtual table between the outer object and the default implementation. Then the composing object call the outer objects methods instead of its own.

// original idea result since A.func1() calling func2() on A would simply call A.func2()
Ae.func1() -> A.func1() -> A.func2()

// updated with using patched vtable // the table would have the updated methods so we a dispatch on func2() on A would call Ae with func2() instead of A. Ae.func1() -> A.func1() -> Ae.func2()

Edit 2:

Mercerenies pointed out Kotlin has it.

It seems kotlin does have support for this, or at least part of it.

Top answer
1 of 5
11
Definitely worth something! In fact, if I understand your idea correctly, Kotlin already did it . If a class Xyz has a field b: Base which implements some interface MyInterface, then Xyz can implement the same interface via class Xyz(val b: Base): MyInterface by b { // ... class body } And you can override any interface methods you want in the class using the usual override keyword, just like normal. (Technically, b needn't even be a field; merely a constructor argument, which is useful if all you need it for is the interface implementation)
2 of 5
4
There are several approaches for interface "inheritance" that also allow the interfaces to have fields. Basically multiple inheritance without the downsides. The biggest question is always: what if multiple interfaces have the same methods with default implementations? Which one is called? Scala traits (mixins) use linearization: the first mentioned trait is the most concrete and overrides all other implementations of traits coming later. The order matters. Pharo traits work differently: they just don't compile if you have a conflict and you need to explicitly rename one of the methods, override it or hide it. In terms of "automatically forward methods to a member": this is a Smalltalk (Pharo) classic. Instead of failing compilation when a method isn't available, the method (message) is passed to a doesNotUnderstand: method, which can just forward the message to some wrapped object. This works because smalltalk is inherently dynamically typed and reflective.
🌐
GitHub
github.com › microsoft › TypeScript › issues › 54979
Interface Default Values · Issue #54979 · microsoft/TypeScript
July 12, 2023 - This feature would agree with the rest of TypeScript's Design Goals. ... The best syntax would be , This suggests x default value is "y" and when x value is not given "y" is used · export interface AccordionColors { x : string = "y" }
Author   wakaztahir
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-interface-default-values
How to set up TypeScript interface Default values | bobbyhadz
February 26, 2024 - We used the Partial utility type to set all of the properties in the Person interface to optional in the function's parameter. Any of the values you pass to the function will override the default values.
Find elsewhere
🌐
EDUCBA
educba.com › home › software development › software development tutorials › typescript tutorial › typescript interface default value
TypeScript Interface Default Value | Learn the Syntax and Examples
April 18, 2023 - Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Interface Default Value ... Entities have to confirm to a syntactical contract called interface. Here, a syntax gets defined by the interface which every entity has to follow. Methods, properties and events are defined by the interface and also are the members of the interface.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Tim Mousk
timmousk.com › blog › typescript-interface-default-value
How To Set Up A TypeScript Interface Default Value? – Tim Mouskhelichvili
March 27, 2023 - An interface works at compile time and is used for type checking. The TypeScript compiler doesn't covert interfaces to JavaScript. Since interfaces only work at compile-time, they cannot be used to set up runtime default values.
🌐
Webdevtutor
webdevtutor.net › blog › typescript-interface-default-method-implementation
Implementing Default Methods in TypeScript Interfaces
The Printer class implements the Printable interface and overrides the defaultPrint() method with a custom implementation.
🌐
Medium
medium.com › @gepphkat › default-implementations-on-interfaces-bd27d3ee168a
Default Implementations on Interfaces | by Jeff Okawa | Medium
March 7, 2018 - These are called “default methods” ( or defender methods). This allow interfaces to define implementations that will be used (as a default) in the situation where a concrete class fails to provide an implementation for that method.
🌐
Delft Stack
delftstack.com › home › howto › typescript › typescript interface default value
How to Interface Default Value in TypeScript | Delft Stack
February 2, 2024 - There is no other way for providing default values for interfaces or type aliases as they are compile-time only, and for the default values, we need runtime support.
🌐
Technical Feeder
technicalfeeder.com › 2022 › 08 › typescript-how-to-set-a-default-value-with-interface
TypeScript How to set a default value with Interface | Technical Feeder
October 26, 2022 - function createMyInterface(options?: Partial<MyInterface>): MyInterface { const defaultValue: MyInterface = { a: 0, b: "default-string", c: null, }; return { ...defaultValue, ...options, } } console.log(createMyInterface()); // { a: 0, b: 'default-string', c: null } console.log(createMyInterface({ a: 999, c: "set-my-string" })); // { a: 999, b: 'default-string', c: 'set-my-string' } You don’t have to use the spread operator for each object creation. It is easier to create an object. What if we use an interface for a class definition? class MyClass implements MyInterface { public a: number = 22; public b: string = "I'm good"; public c: unknown = { value: 55 }; }
🌐
Graphite
graphite.com › guides › typescript-interfaces
Understanding interfaces in TypeScript - Graphite
... In this example, Customer extends two discrete interfaces, combining the properties of Person and Contact. Interfaces themselves do not hold default values in TypeScript; they are strictly for typing.
🌐
Convex
convex.dev › core concepts › object-oriented programming (oop) › interfaces
Interfaces | TypeScript Guide by Convex
Default recommendation: Use type for most cases. It's more flexible and can handle unions, intersections, and mapped types. Use interface specifically when: You're defining object inheritance hierarchies where extends gives you better performance ...
🌐
TestMu AI Community
community.testmuai.com › ask a question
Defaulting Unspecified Interface Properties to Null in TypeScript - Ask a Question - TestMu AI Community
July 25, 2024 - I have the following TypeScript interface: interface IX { a: string; b: any; c: AnotherType; } I declare a variable of this type and initialize all the properties with default values: let x: IX = { a: 'abc', b: null, c: null }; Later, I assign ...
🌐
LogRocket
blog.logrocket.com › home › understanding and using interfaces in typescript
Understanding and using interfaces in TypeScript - LogRocket Blog
October 17, 2024 - This factory function uses the nullish coalescing operator (??) to assign default values when properties are not provided. This operator was introduced in TypeScript 3.7 (together with optional chaining) and provides a more concise way to handle ...
🌐
Quora
quora.com › What-are-the-default-values-of-a-Typescript-Interface
What are the default values of a Typescript Interface? - Quora
Answer (1 of 2): An interface describes the shape of data and isn’t data itself. If you compile a .ts file that only has an interface in it, it won’t generate any code. So, interfaces have no data and no default value.