Quantcast
Viewing all articles
Browse latest Browse all 4838

How to declare optional instance property to EmberObject in ES6 class in Typescript?

@Lupestro wrote:

Situation: An EmberObject declared as an ES6 class has an instance property. The create({…}) may or may not supply a value. If the property doesn’t have a value upon construction, the constructor will give it a value. I am using strict TypeScript.

  • If I use item : ItemType, the if (!this.item) in the constructor will get a type error.
  • If I use item?: ItemType, all my methods will require guard clauses when using it.
  • If I use item! : itemType, I will get no errors, but nothing will verify that the constructed property has a value. (My declaration merely asserts that - trust me - it does. If I trusted me, I wouldn’t be using TypeScript. Image may be NSFW.
    Clik here to view.
    :slight_smile:
    )

If I use a POJO built using a “real constructor” rather than an EmberObject with create({}), does TypeScript offer a better way to express this intention?

Or is the cleanest option to use two values, an itemParm?: ItemType for the external input, and an item: ItemType that is initialized in the constructor and used throughout the rest of the class? The problem here is that the naming is guaranteed to be terrible.

Is there anything that can be done with decorators to get the desired effect?

Posts: 2

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 4838

Trending Articles