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.
No there is not.
An interface-declaration only exists at compile-time, so the only time to do something like that is when compiling. Unfortunately, the compiler does not provide any language construct to do this, nor any way to extend the compilation process.
One way to get around this problem, would be to do some code-generation; Add a function that creates an object with the correct structure. The problem with this approach, is that you either have to parse TypeScript code, or some Domain Specific Language.
Read something like this:
And generate something like: