Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default interface object

Tags:

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.

like image 464
N. Taylor Mullen Avatar asked Nov 10 '12 22:11

N. Taylor Mullen


People also ask

Can an interface have a default value?

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.

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 }, };

What is the interface in TypeScript?

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.

Can we have interface with optional and default properties in TypeScript?

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.


1 Answers

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

like image 184
Matija Grcic Avatar answered Sep 24 '22 00:09

Matija Grcic