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?
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.
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 }, };
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.
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.
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() { }
}
With C#8, interfaces can have a default implementation. https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With