Ano*_*123 7 javascript json structural-typing typescript angular
这样做有什么区别
export class Comment {
likes: string;
comment: string;
constructor(likes: string, comment: string){
this.comment = comment;
this.likes = likes;
}
}
Run Code Online (Sandbox Code Playgroud)
还有这个
export interface CommentInterface {
likes: string;
comment: string;
}
Run Code Online (Sandbox Code Playgroud)
关于声明可观察类型
register: Observable<CommentInterface[]> {
return this.http.get()
}
Run Code Online (Sandbox Code Playgroud)
Alu*_*dad 11
正如JB Nizet非常正确指出的那样,HTTP请求产生的反序列化JSON值永远不会是类的实例.
虽然classTypeScript中构造的双重角色(见下文)使得可以使用a class来描述这些响应值的形状,但这是一种不好的做法,因为响应文本将被反序列化为纯JavaScript对象.
请注意,在整个答案中我不使用类型,Comment.likes因为在问题中你将它作为一个类型string,但它对number我来说感觉像是一个,所以我把它留给了读者.
JavaScript和TypeScript中的类声明:
在JavaScript中,一个类声明
class Comment {
constructor(likes, comment) {
this.likes = likes;
this.comment = comment;
}
}
Run Code Online (Sandbox Code Playgroud)
创建一个可以实例化的值,new以充当本质上的工厂.
在TypeScript中,类声明会创建两件事.
第一个是与上述完全相同的JavaScript类值.第二种是描述通过写入创建的实例的结构的类型
new Comment(4, 'I love your essays')
Run Code Online (Sandbox Code Playgroud)
然后,第二个工件(类型)可以用作类型注释,例如在您的示例中
register(): Observable<Comment[]> {
return this.http.get()
}
Run Code Online (Sandbox Code Playgroud)
这表示register返回实例Observable数组Comment class.
现在假设您的HTTP请求返回以下JSON
[
{
"likes": 4,
"comment": "I love you oh so very much"
},
{
"likes": 1,
"comment": "I lust after that feeling of approval that only likes can bring"
}
]
Run Code Online (Sandbox Code Playgroud)
但是方法声明
register(): Observable<Comment[]>;
Run Code Online (Sandbox Code Playgroud)
虽然它正确地允许呼叫者写
register().subscribe(comments => {
for (const comment of comment) {
if (comment.likes > 0) {
likedComments.push(comment);
}
}
});
Run Code Online (Sandbox Code Playgroud)
这一切都很好,很遗憾,它也允许调用者编写代码
getComments() {
register().subscribe(comments => {
this.comments = comments;
});
}
getTopComment() {
const [topComment] = this.comments.slice().sort((x, y) => y < x);
// since there might not be any comments, it is likely that a check will be made here
if (topComment instanceof Comment) { // always false at runtime
return topComment;
}
}
Run Code Online (Sandbox Code Playgroud)
由于注释实际上不是Comment类的实例,因此上述检查将始终失败,因此代码中存在错误.但是,typescript不会捕获错误,因为我们说这comments是一个Comment类的实例数组,这将使检查有效(回想一下,response.json()返回any可以转换为任何类型而没有警告,因此在编译时一切正常.
但是,如果我们宣布评论为 interface
interface Comment {
comment: string;
likes;
}
Run Code Online (Sandbox Code Playgroud)
然后getComments将继续进行类型检查,因为它实际上是正确的代码,但是getTopComment会在if语句的编译时引发错误,因为正如许多其他人所指出的那样interface,不能像使用编译时构造一样,不能使用它是执行instanceof检查的构造函数.编译器会告诉我们我们有错误.
备注:
除了给出的所有其他原因之外,在我看来,当你在JavaScript/TypeScript中有一些代表普通旧数据的东西时,使用类通常是矫枉过正的.它创建了一个带有原型的函数,并且有许多我们不太可能需要或关心的其他方面.
如果您使用对象,它还会抛弃您默认获得的好处.这些好处包括用于创建和复制对象的语法糖以及TypeScript对这些对象类型的推断.
考虑
import Comment from 'app/comment';
export default class CommentService {
async getComments(): Promse<Array<Comment>> {
const response = await fetch('api/comments', {httpMethod: 'GET'});
const comments = await response.json();
return comments as Comment[]; // just being explicit.
}
async createComment(comment: Comment): Promise<Comment> {
const response = await fetch('api/comments', {
httpMethod: 'POST',
body: JSON.stringify(comment)
});
const result = await response.json();
return result as Comment; // just being explicit.
}
}
Run Code Online (Sandbox Code Playgroud)
如果Comment是一个接口,我想使用上面的服务来创建一个注释,我可以这样做
import CommentService from 'app/comment-service';
export async function createComment(likes, comment: string) {
const commentService = new CommentService();
await commentService.createCommnet({comment, likes});
}
Run Code Online (Sandbox Code Playgroud)
如果Comment是一类,我需要通过迫使该引进一些锅炉板import的Comment.当然,这也增加了耦合.
import CommentService from 'app/comment-service';
import Comment from 'app/comment';
export async function createComment(likes, comment: string) {
const commentService = new CommentService();
const comment = new Comment(likes, comment); // better get the order right
await commentService.createCommnet(comment);
}
Run Code Online (Sandbox Code Playgroud)
这是两个额外的行,一个涉及依赖于另一个模块只是为了创建一个对象.
现在,如果Comment是一个接口,但我想要一个复杂的类,在我将它提供给我的服务之前进行验证,我仍然可以拥有它.
import CommentService from 'app/comment-service';
import Comment from 'app/comment';
// implements is optional and typescript will verify that this class implements Comment
// by looking at the definition of the service method so I could remove it and
// also remove the import statement if I wish
class ValidatedComment implements Comment {
constructor(public likes, public comment: string) {
if (Number(likes) < 0 || !Number.isSafeInteger(Number(likes))) {
throw RangeError('Likes must be a valid number >= 0'
}
}
}
export async function createComment(likes, comment: string) {
const commentService = new CommentService();
const comment = new ValidatedComment(likes, comment); // better get the order right
await commentService.createCommnet(comment);
}
Run Code Online (Sandbox Code Playgroud)
简而言之,有许多理由使用an interface来描述响应的类型以及使用TypeScript时与HTTP服务交互的请求.
注意:您也可以使用type声明,该声明同样安全且稳健,但它不那么惯用,并且工具interface经常使它更适合这种情况.
与大多数其他OOP语言一样:对于类,您可以创建实例(通过其构造函数),而不能创建接口实例.
换句话说:如果您只返回反序列化的JSON,那么使用该接口以避免混淆是有意义的.让我们假设您foo为您的Comment班级添加一些方法.如果register声明您的方法返回a,Comment那么您可能会认为您可以调用fooregister的返回值.但是这不会起作用,因为register有效返回的只是反序列化的JSON而没有foo在Comment类上实现.更具体地说,它不是您Comment班级的实例.当然,你也可能不小心foo在你的方法中声明了这个方法CommentInterface,它仍然无法正常工作,但是那个foo方法没有真正的代码,只是没有被执行,这样可以更容易地推断你的通话的根本原因对foo不工作.
另外在语义层面上考虑它:声明返回接口保证在接口上声明的所有内容都存在于返回值上.声明返回一个类实例保证你......好吧......返回一个类实例,这不是你正在做的事情,因为你正在返回反序列化的Json.
| 归档时间: |
|
| 查看次数: |
1235 次 |
| 最近记录: |