Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default value for properties of Interface?

I have an Interface which contains one property. I need to set the default value for that property. How to do that?. Also is it good practice to have a default value for a property in Interface? or here using an abstract class instead is a apt one?

like image 503
Mohan Avatar asked Oct 12 '11 05:10

Mohan


People also ask

Can an interface have default values?

It should be noted that you can't explicitly set default values in an interface, because interfaces and types get removed during compilation. They don't exist at runtime, so we can only leverage them during the development process.

How do I give a default value to a TypeScript interface?

Normal way to set a default value to a property is the following. interface MyInterface { a: number; b: string; c: unknown; } const data1: MyInterface = { a: 0, b: "default-string", c: "something", }; const data2: MyInterface = { a: 0, b: "default-string", c: { value: 1 }, };

Can we have interface with default properties in TypeScript?

In TypeScript, interfaces represent the shape of an object. They support many different features like optional parameters but unfortunately do not support setting up default values.

Can we assign value to interface?

No, we can't change the value of an interface field because interface fields are final and static by default. We will get compile time error, if we try to change the interface field value.


2 Answers

You can't set a default value to a property of an interface.

Use abstract class in addition to the interface (which only sets the default value and doesn't implement anything else):

    public interface IA {
        int Prop { get; }

        void F();
    }

    public abstract class ABase : IA {
        public virtual int Prop
        {
            get { return 0; }
        }

        public abstract void F();
    }

    public class A : ABase
    {
        public override void F() { }
    }
like image 90
Petar Ivanov Avatar answered Sep 30 '22 17:09

Petar Ivanov


With C#8, interfaces can have a default implementation. https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/

like image 22
Ibrahim ULUDAG Avatar answered Sep 30 '22 16:09

Ibrahim ULUDAG