我正在使用TS来构建节点快速API。我区分model
和viewmodel
类。 Post
模型类可以有多个视图模型表示。
但是如何从模型转换为viewmodel类?我可以创建一个创建新viewmodel对象的方法。但是有可能只是转换为另一种类型吗?
示例
Post.ts
export interface IPost {
id: number;
author: string;
heading: string;
body: string;
}
/**
* Class to model a blog post
*/
export class Post implements IPost {
public id: number;
public author: string;
public heading: string;
public body: string;
constructor(id: number, author: string, heading: string, body: string) {
this.id = id;
this.author = author;
this.heading = heading;
this.body = body;
}
}
PostVM.ts
export interface IPostVM {
id: number;
author: string;
text?: string;
}
/**
* Class to model a blog post
*/
export class PostVM implements IPostVM {
public id: number;
public author: string;
public text?: string;
constructor(id: number, author: string, body: string) {
this.id = id;
this.author = author;
this.text = body;
}
}
App.ts
// This is NOT working:
const post: IPost = this.dao.getPostById(id);
const postVM: IPostVM = post as PostVM;
结果:
{
"author": "Ole",
"body": "Dette er en test på body tekst.",
"heading": "Overskrift 1",
"id": 1
}
应该是:
{
"id": 1
"author": "Ole",
"text": "Overskrift 1",
}
答案 0 :(得分:2)
你不能只是"演员"因为,评论说,除非你自己写,否则没有办法知道你希望如何转换课程。
正如你所说,你可以做的最好的事情就是为班级编写一个函数:
export class Post implements IPost {
<...>
toPostVM() {
return new PostVM(this.id, this.author, this.body);
}
}
然后在你的App.ts中你可以做到:
const postVM: IPostVM = post.toPostVM();