英文:
Optional properties behavior in TypeScript constructor arguments and interface
问题
- 这种行为是 TypeScript 中的意图吗,允许将带有可选属性的对象传递给期望非可选参数的构造函数吗?
- TypeScript 是否应该在这种情况下引发警告或错误,以在开发过程中执行更严格的类型检查?
- 在构建期望非可选参数的对象时,处理可选属性的最佳做法是什么?
英文:
I'm working on a TypeScript project where I have encountered an interesting behavior regarding optional properties in constructor arguments and interfaces. It seems that TypeScript allows me to pass an object with optional properties to a constructor, even when the constructor's argument type is a non-optional type.
// 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
Expected Behavior:
I expected TypeScript to raise a warning or error when passing an object with optional properties to the Payment constructor because the email property in the Payment class is not marked as optional.
Actual Behavior:
No warnings or errors are raised by TypeScript when I pass an object with optional properties to the Payment constructor, even though the constructor expects a non-optional string argument for the email property.
Questions:
- Is this behavior intentional in TypeScript, allowing optional properties to be passed to a constructor expecting non-optional arguments?
- Should TypeScript raise a warning or error in such cases to enforce stricter type checks during development?
- What are the best practices to handle optional properties when constructing objects that expect non-optional arguments?
答案1
得分: 1
最有可能的原因是你在tsconfig中没有将"strict"设置为true。 TypeScript只是JavaScript的一个超级类型。所以在其最基本的层面上,它将能够正常编译为JavaScript。JavaScript没有"可选参数"的概念,只是简单地不提供它们。这种松散的TypeScript编译对于想要将JS项目转换为TS的情况非常有用。它允许你像TS一样编译JS,而不会导致一切失败,因此你可以逐步采用。
但是,如果在配置中将strict设置为true,TS编译器将假定一切都具有完全可靠的类型,并且不会编译任何在运行时不安全的内容。
英文:
The most likely reason for this is you do not have "strict" set to true in your tsconfig. Typescript is just a super type of Javascript. So at it's most fundamental level, this will be able to compile to Javascript just fine. Javascript has no concept of "optional params" beyond simply not supplying them. This lax compilation of Typescript is useful if you have a JS project you want to convert to TS. It lets you compile JS like it is TS without everything failing so you can adopt slowly.
If you set strict to true in your config though, the TS compiler will assume EVERYTHING is fully and reliably typed, and will not compile anything that is not safe at runtime.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论