TypeScript:将结果强制转换为自定义类型无效
我对Person类型的定义如下TypeScript:将结果强制转换为自定义类型无效,typescript,casting,Typescript,Casting,我对Person类型的定义如下 import moment from "moment"; export default class Person { constructor() { this.id = -1; this.name = ""; this.dob = new Date(); this.gender = "M"; this.photo = ""; this.salary = 0.0
import moment from "moment";
export default class Person {
constructor() {
this.id = -1;
this.name = "";
this.dob = new Date();
this.gender = "M";
this.photo = "";
this.salary = 0.0;
}
public id: number;
public name: string;
public dob: Date;
public get dobString(): string{
return moment(this.dob).toString();
};
public gender: string;
public photo: string;
public salary: number;
}
在上面的Person类型中,您可以看到我有一个只读属性dobString(),它几乎以字符串格式返回日期
现在我有了一个get方法,它返回记录集合。我正在将集合强制转换为
,但结果不包括属性dobString()。你能在下面验证我的代码并让我知道我遗漏了什么吗
getAll (req: Request, res: Response, next: NextFunction) {
var pageNumber = req.query.pageNumber;
var pageSize = req.query.pageSize;
db.query("CALL person_selectall(?, ?, @total); SELECT @total as TotalRecords;", [pageNumber, pageSize], (err: Error, rows: any[], fields: any) => {
let result = new PageResult<Person>(pageSize, pageNumber, 0);
if (!err) {
result.IsSuccessful = true;
result.TotalRecords = rows[2][0].TotalRecords;
result.Data = <Person[]> rows[0];//result.Data is of type Person[]
res.send(result);
} else {
result.IsSuccessful = false;
result.TotalRecords = 0;
result.ReasonForFailure = JSON.stringify(err);
result.Data = [];
res.send(result);
}
});
}
谢谢,
Hemant.result.Data=行[0]代码>
请记住,当typescript被传输时,所有类型注释都会消失,剩下的javascript会显示result.Data=rows[0]
。该代码不会向对象添加任何不存在的属性
使用像
这样的类型断言的目的不是对数据进行任何更改。这样做的目的是告诉typescript“我比你更清楚,所以不要在这里检查我的类型”。如果你真的比typescript更懂,那就没问题了。但是,如果您断言对象具有dobString函数,而实际上它没有,typescript将只信任您,并且无法指出错误。那么有没有办法让我的结果包括自定义类型的所有成员?如果是这样的话,你能分享这个代码片段来实现吗?好吧,如果这只是javascript,你想做什么?可能会调用新人一次或多次,从行中传入数据。我不确定您到底想要什么代码,因为我不知道行的结构,而且您的Person构造函数看起来不像是在属性中传递的设置。看起来我必须在循环中将数据从行映射到自定义类型集合。让我知道是否有更好的方法aroundI用临时解决方案更新我的请求。
const personArray = rows[0].map((row: any) => {
const person = new Person();
person.Id = row.id;
person.Name = row.name;
person.Gender = row.gender;
person.Dob = row.dob;
person.DobString = moment(person.Dob).format(config.get("format.date"));
person.Photo = row.photo;
person.Salary = row.salary;
person.CreatedDate = row.createddate;
person.CreatedDateString = moment(person.CreatedDate).format(config.get("format.datetime"));
person.ModifiedDate = row.modifieddate;
person.ModifiedDateString = person.ModifiedDate === null ? null : moment(person.ModifiedDate).format(config.get("format.datetime"));
return person;
});
result.Data = personArray;