[英]Why TypeScript doesn't infer type from function signature?
I've an issue in my Angular service with TypeScript type inferance.我的 Angular 服务存在 TypeScript 类型推断的问题。 I'm new to TypeScript and I wonder why this code:
我是 TypeScript 的新手,我想知道为什么这个代码:
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? amount
不应该是数字吗?
Edit: Here is the context of PaymentComponent:编辑:这是 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.有效负载在运行时以纯 Javascript 解释......所以无论后端响应有什么都将在变量中设置。
the angular services and TypeScript itself do not remove the additional attributes from the json payload. angular 服务和 TypeScript 本身不会从 json 有效负载中删除附加属性。
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.您可以更改您的后端以不提供您不希望拥有的其他属性,或者自定义您的服务以删除这些属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.