0

I've an issue in my Angular service with TypeScript type inferance. I'm new to TypeScript and I wonder why this code:

initializeTransaction(user: User, amount: number) {
  let params = {
    userId: user.id,
    amount: amount
  };
  return this.http.post<any>('/api/v1/payment/transaction/initialize', params);
}

where:

export class User {
  id: number;
}

gives me this payload:

{"userId":1,"amount":"2000"}

Shouldn't amount be a number?

Edit: Here is the context of PaymentComponent:

export class PaymentComponent implements OnInit {

  private user = new User();

  submitted = false;
  redirecting = false;
  paymentForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private paymentService: PaymentService,
    private userService: UserService
  ) {
    this.userService.me().subscribe(response => this.user = response);
  }

  ngOnInit() {
    this.paymentForm = this.formBuilder.group({
      amount: ['', [Validators.required, Validators.pattern("^[0-9]*$")]]
    });
  }

  get f() { return this.paymentForm.controls; }

  onPay() {
    this.submitted = true;

    if (this.paymentForm.invalid) {
      return false;
    }

    this.redirecting = true;
    this.paymentService.initializePage(this.user, this.f.amount.value)
      .subscribe(response => window.location.href = response.redirectUrl);
  }

}
3
  • 3
    types don't change runtime behavior, if amount got to be a string somehow it will still be a string when you assign it to User Commented Oct 29, 2019 at 8:48
  • 1
    When your code runs in the browser typescript does not exists anymore, it only does at development time. When your code is built (transpiled) into javascript there is no types anymore. Commented Oct 29, 2019 at 8:51
  • I've added the context in my question. Should I write +this.f.amount.value instead of this.f.amount.value?
    – didil
    Commented Oct 29, 2019 at 8:59

1 Answer 1

1

the payload is interpreted in pure Javascript at runtime... so whatever the backend response has would be set in the variable.

the angular services and TypeScript itself do not remove the additional attributes from the json payload.

you can either change your backend to not serve the additional attributes you wouldn't want to have or customize your service to remove the attributes.

3
  • payload is usually about responses, are you talking about the value of the variable params?
    – The Fabio
    Commented Oct 29, 2019 at 8:59
  • I'm talking about the "Request payload" in my Firefox debugger tool.
    – didil
    Commented Oct 29, 2019 at 9:01
  • your form value is a string, you could convert to number with amount: parseInt(amount) in your service
    – The Fabio
    Commented Oct 29, 2019 at 9:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.