微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 使用类和接口有什么区别?

这样做有什么区别
export class Comment {
  likes: string;
  comment: string;

  constructor(likes: string,comment: string){
    this.comment = comment;
    this.likes = likes;
  }
}

还有这个

export interface CommentInterface {
  likes: string;
  comment: string;
}

关于声明一个可观察的类型

register: Observable<CommentInterface[]> {
    return this.http.get()
}

解决方法

正如JB Nizet非常正确指出的那样,HTTP请求产生的反序列化JSON值永远不会是类的实例.

虽然TypeScript中类构造的双重角色(见下文)使得可以使用类来描述这些响应值的形状,但这是一种不好的做法,因为响应文本将被反序列化为纯JavaScript对象.

请注意,在整个答案中我不使用Comment.likes的类型,因为在问题中你将它作为一个字符串,但它对我来说感觉像一个数字,所以我把它留给了读者.

JavaScript和TypeScript中的类声明:

在JavaScript中,一个类声明

class Comment {
  constructor(likes,comment) {
    this.likes = likes;
    this.comment = comment;
  }
}

创建一个可以使用new实例化的值,以充当本质上的工厂.

在TypeScript中,类声明会创建两件事.

一个是与上述完全相同的JavaScript类值.
第二种是描述通过写入创建的实例的结构的类型

new Comment(4,'I love your essays')

然后,第二个工件(类型)可以用作类型注释,例如在您的示例中

register(): Observable<Comment[]> {
    return this.http.get()
}

这表示寄存器返回一个Observable of Arrays of Comment类实例.

现在假设您的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"
  }
]

但是方法声明

register(): Observable<Comment[]>;

虽然它正确地允许呼叫者写

register().subscribe(comments => {
  for (const comment of comment) {
    if (comment.likes > 0) {
      likedComments.push(comment);
    }
  }
});

这一切都很好,不幸的是它也允许调用者编写代码

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;
  }
}

由于注释实际上不是Comment类的实例,因此上述检查将始终失败,因此代码中存在错误.但是,typescript不会捕获错误,因为我们说注释是Comment类的一个实例数组,这将使检查有效(回想一下,response.json()返回任何可以转换为任何类型而没有警告的内容在编译时一切都很好.

但是,如果我们已将注释声明为接口

interface Comment {
  comment: string;
  likes;
}

然后getComments将继续进行类型检查,因为它实际上是正确的代码,但getTopComment将在编译时在if语句中引发错误,因为正如许多其他人所指出的,接口是一个仅编译时的构造,不能用作执行检查实例的构造函数.编译器会告诉我们我们有错误.

备注:

除了给出的所有其他原因之外,在我看来,当你在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.
  }
}

如果Comment是一个接口,我想使用上面的服务来创建一个注释,我可以这样做

import CommentService from 'app/comment-service';

export async function createComment(likes,comment: string) {    
  const commentService = new CommentService();

  await commentService.createCommnet({comment,likes});
}

如果评论一个类,我需要通过导入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);
}

这是两个额外的行,一个涉及依赖于另一个模块只是为了创建一个对象.

现在,如果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);
}

简而言之,使用接口来描述响应类型以及使用TypeScript时与HTTP服务交互的请求有很多原因.

注意:您也可以使用类型声明,它同样安全且强大,但它不那么惯用,并且界面周围的工具通常使它更适合这种情况.

原文地址:https://www.jb51.cc/js/159808.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐