简体   繁体   中英

Why TypeScript doesn't infer type from function signature?

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);
  }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM