Is there any way to create a default interface object?
Example:
interface myInterface {
A: string;
B: string;
C: number;
D: CustomType; // A custom class
}
Usually you'd create an object of this interface by:
var myObj: myInterface = {
A: "",
B: "",
C: 0,
D: null
}
However it'd be nice if there was some syntactic sugar to do it like this:
var myObj = new myInterface;
// OR
var myObj = default(myInterface);
From my research I haven't found a way to do this; but I'm hoping that I've just missed something.
Since interfaces only work at compile-time, they cannot be used to set up runtime default values. Luckily, TypeScript provides a workaround for this. By using the TypeScript pick utility type, we can select properties from an interface and provide default values for them.
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 }, };
Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow. Classes that are derived from an interface must follow the structure provided by their interface. The TypeScript compiler does not convert interface to JavaScript.
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.
You can use a slightly different syntax and get all the type checking and IntelliSense.
interface IUserModel{
Name: string;
Age: number;
Email: string;
IsActive: boolean;
}
var user = <IUserModel>{};
You make an empty user object but TypeScript compiler is still checking that you have valid properties on the object and it still provides code completion.
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