typescript - Object.assign 将日期字符串分配给模型中的 Date 类型
我不明白为什么我的模型没有抛出错误,而是自由地将我从 httpClient 调用中得到的日期字符串分配给模型中的 Date 类型。
这是代码
// Data model
export class Data {
purpose: string = null;
percentSold: number = null;
originalTerm: number = null;
originatedBy: string = null;
noteDate: Date = null;
productType: string = null;
maturityDate: Date = null;
noteAmount: number = null;
disburseDate: Date = null;
interestRate: number = null;
number: number = null;
branch: string = null;
principal: number = null;
amountAdvanced: number = null;
code: Code;
mailingAddress: AccountAddress;
constructor() {
this.code = new Code();
this.mailingAddress = new AccountAddress();
}
}
let data = new Data();
Object.assign(data, someObjectFromRouteCall);
// data object from Data model has noteDate and disimburseDate still be of type string答案#1
赋值发生在运行时,而 TypeScript 在运行时并不活跃。它只在编译期间进行类型检查。
你有两个选择:
- 通过 JavaScript 手动进行类型检查/转换。
- 在服务器端和客户端使用完全相同的类型。如果你选择 TypeScript 作为后端语言,这可以很容易实现,但只要所选语言有类/接口自动生成器,使用其他后端语言理论上也可以实现。但是,要从这种方法中受益,你需要不使用
Date对象,而是处理日期字符串。