繁体   English   中英

为什么 TypeScript 不能从 function 签名推断类型?

[英]Why TypeScript doesn't infer type from function signature?

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

}

有效负载在运行时以纯 Javascript 解释......所以无论后端响应有什么都将在变量中设置。

angular 服务和 TypeScript 本身不会从 json 有效负载中删除附加属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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