0

I am looking for a little clarity. I have a typescript (I'm using 1.7) function that is tied to the change event of a select option / drop down in the html:

    toggleWorker(stsID: number): void {
    // get status object by selected staus ID
    let cStatus: Status = this.stsList.filter((s: Status) => s.StatusID === stsID)[0];
    // if status requires a worker to be assigned then toggle requireWorker
    if (cStatus.RequireWorker) {
        this.requireWorker = true;
    } else if (!cStatus.RequireWorker) {
        this.requireWorker = false;
    }
}

here is the HTML declaration:

   <div class="large-3 columns">
       <label >Trade Status
           <select id="StatusID" 
               [(ngModel)]="currentTrade.StatusID"
               [ngFormControl]="shiftForm.controls['StatusID']"
               (change)="toggleWorker($event.target.value)" >
               <option *ngFor="#sts of stsList" value="{{sts.StatusID}}"
                  >{{sts.Title}}</option>
           </select>
       </label> 
   </div>

here is the class of the status object so you can see that the StatusID is a type number:

export class Status {

StatusID: number;
PortalID: number;
Title: string;
Code: string;
RequireWorker: boolean;

constructor(obj?: any) {
    this.StatusID = obj && obj.StatusID || 0;
    this.PortalID = obj && obj.PortalID || 0; 
    this.Title = obj && obj.Title || null;
    this.Code = obj && obj.Code || null;
    this.RequireWorker = obj && obj.RequireWorker || false;
}

}

I have a sample fiddle where this works perfectly.

But when I tried to use this in my angular2 app it did not work unless i explicitly converted the type of the function parameter. See the following change:

let cStatus: Status = this.stsList.filter((s: Status) => s.StatusID === Number(stsID))[0];

Notice the addition of Number(stsID)

QUESTION: Can someone help me understand what is going on here. Is the type declaration of the function parameter only for internal typechecking, I assumed it would perform a conversion to that type.

I hope that makes sense.

Thanks

J King
  • 4,108
  • 10
  • 53
  • 103

1 Answers1

1

As you assumed types are only for static type checking. There is no conversion going on. You need to convert explicitly.

There is also type casting where you express that type checking can assume that a value is of a certain type but that also doesn't convert a value if it actually is not of that type.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • thanks, so what is best practice for type conversions in this situation? Do you try to convert function parameters as the first step in the function for all parameters? – J King Apr 07 '16 at 15:57
  • 1
    I guess I would create a custom ControlValueAccessor like shown in http://stackoverflow.com/questions/31879497/angular2-radio-button-binding or a getter/setter that does the conversion. – Günter Zöchbauer Apr 07 '16 at 16:01