Typescript – Default interface object

typescript

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.

Best Answer

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.

enter image description here

enter image description here