为什么TypeScript不能从函数签名中推断类型?

时间:2019-10-29 08:46:17

标签: angular typescript

我的Angular服务存在TypeScript类型推断问题。我是TypeScript的新手,我想知道为什么要这段代码:

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

其中:

export class User {
  id: number;
}

给我这个有效载荷:

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

amount不是数字吗?

编辑: 这是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);
  }

}

1 个答案:

答案 0 :(得分:1)

有效负载在运行时用纯Javascript解释...因此,无论后端响应如何,都将在变量中进行设置。

角度服务和TypeScript本身不会从json有效负载中删除其他属性。

您可以更改后端以不提供您不希望拥有的其他属性,也可以自定义服务以删除这些属性。