happyZZR1400
happyZZR1400

Reputation: 2415

How events should be defined with typescript?

I'm using angular1.5 with typescript. I'm trying to follow todd-motto style guide about one-way-dataflow

I have two components: app (statefull) and its child manage-dialog

app contains list of events

manage-dialog its a form that changes time property (hours and minutes) for all selected events.

The change is passed back as event.

controller: class ManageDialog {
  public evts:Array<Event>;

  save() {
    this.onEdited({$event:{h:this.h,m:this.m}});//i guess this is not correct in typescript
  }
}

Since i'm writing typescript - should i define some special type for object pushed inside event (may be interface)?

Or may be correct thing is to define type for event itself?

(I have lot of "bulk" forms which should edit different properties - so is it correct to define lot of types?)

plnkr that demonstrates my problem

Upvotes: 0

Views: 404

Answers (3)

netas85
netas85

Reputation: 21

I think Sefi Ninio raises a good point. If you're insisting of making everything typed, then you can use the below form:

class ItemsInEvent {
      constructor(public item:string){}
}
class BindedEvent {
      constructor(public $event:ItemsInEvent){}
}
// Inside your controller:
export class MyCtrl {
       public bindedEvent: (BindedEvent)=>void;//Declare the bound method 
       public someMethod():void {
              let myBindedItem:ItemsInEvent = new ItemsInEvent ("foo");
              let myBindedEvent:BindedEvent = new BindedEvent (myBindedItem);
              // Trigger event
              this.bindedEvent(myBindedEvent);
       }
}
// Component definition:
export class MyComponent implements IComponentOptions {
       bindings: {
               bindedEvent: '&'
       }
}

Upvotes: 2

Ran
Ran

Reputation: 755

I would separate the data from the event itself and use generics for that matter.

The event can be a generic class that has a member named "data" with the type parameter, and then tha data can pass.

p.s the drag & drop events uses this approach in javascript (well, not the generic part which is typescript).

Upvotes: 0

Sefi Ninio
Sefi Ninio

Reputation: 437

Technically speaking, I think it is correct. You are using TypeScript for the usage of types, so use them - especially if you have a lot of places in the code where you use them (like your Event object).

I would, however, be careful not to go overboard. I wouldn't want to create an object type (interface) for each and every object I use - that would get tiresome fast.

It is not the "strictly typed" approach adopted by languages like Java (where everything is a type), but kind of a middle ground between type safety and sanity :)

Upvotes: 1

Related Questions