我正在处理一个类型脚本项目,在该项目中,我遇到了一个关于构造函数参数和接口中的可选属性的有趣行为.看起来,类型脚本允许我将具有可选属性的对象传递给构造函数,即使构造函数的参数类型是非可选类型.
// StartPaymentReq Interface
export interface StartPaymentReq {
email?: string;
}
// Payment Class
export class Payment {
email: string;
constructor(email: string) {
this.email = email;
}
}
// Inside some function or method
const { email }: StartPaymentReq = req.body; // Destructuring from req.body, email inferred as `string | undefined`
const payment = new Payment(email); // No TypeScript warning or error even if email can be undefined
预期行为:
我预计在将带有可选属性的对象传递给Payment构造函数时,TypeScrip会引发警告或错误,因为Payment类中的Email属性没有标记为可选.
实际行为:
当我将带有可选属性的对象传递给Payment构造函数时,Type脚本不会引发警告或错误,即使构造函数需要Email属性的非可选字符串参数.
问题:
- 这种行为在类型脚本中是故意的吗,允许将可选属性传递给期望非可选参数的构造函数?
- 在这种情况下,TypeScrip是否应该发出警告或错误,以在开发过程中强制执行更严格的类型判断?
- 在构造需要非可选参数的对象时,处理可选属性的最佳实践是什么?