Angular 2 instantiate class with empty values

前端 未结 2 1942
执笔经年
执笔经年 2021-01-19 08:17

How do you instantiate the members as class with empty values?

Plunkr

I instantiate with

public members = new MemberClass();

2条回答
  •  不知归路
    2021-01-19 09:02

    Keep in mind that you're using Interfaces there, not classes. In Typescript, as in Javascript, an empty object is just {}

    So, to do what you're looking for, try this: let history: History = { Id:"", CaseNumber:""};

    If you try to leave out any of those properties, you'll get an error that they're required. If you want properties of an interface to be optional when instantiating, update your interface like this: CaseNumber?: string;

    Find more in the handbook.

    To further clarify: a class is a concrete type that you can instantiate and use as you would in any language. If you need a constructor or default values on your properties, you should use export class MyType {}.

    However, in my experience, I've found interfaces in Typescript to be more useful than classes in many cases. The reason for this is that you can code against them at dev-time, but they aren't included in your bundles when you ship (N.B. this ENTIRELY depends on your use-case).

提交回复
热议问题