• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[TypeScript]InterfaceandClass

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

When to use Interface and when to use Class.

Let's see one example:

export interface Lesson {
 courseId: string;
 description: string;
 duration?: string;
 longDescription?: string;
 tags: string | string[];
 url?: string;
 videoUrl: string;
 }

export class Lesson {
  constructor(
              public courseId: string,
              public description: string,
              public duration: string,
              public longDescription: string,
              public tags: string | string[],
              public url: string,
              public videoUrl: string) {
  }
}

We have an Interface 'Lesson' and a Class 'Lesson'. At this point, I would love to say, there is no differece between using interface or using Class. Actually I prefer Interface in this case, because its short-hand syntax.

 

We when you want to add more functionalities, you need to using Class instead of Interface.

For example:

export class Lesson {
  constructor(public $key: string,
              public courseId: string,
              public description: string,
              public duration: string,
              public longDescription: string,
              public tags: string | string[],
              public url: string,
              public videoUrl: string) {
  }

  get hasVideoUrl() {
    return !!this.videoUrl;
  }

  get hasMultiTags() {
    if (this.tags instanceof Array) {
      return true;
    } else {
      return false;
    }
  }

  static fromJsonList(array): Lesson[] {
    return array.map(Lesson.fromJson);
  }

  static fromJson({
    $key,
    courseId,
    description,
    duration,
    longDescription,
    tags,
    url,
    videoUrl
  }): Lesson {
    return new Lesson($key,
      courseId,
      description,
      duration,
      longDescription,
      tags,
      url,
      videoUrl)
  }
}

We add two getter and setter, hasMuliTags and hasVideoUrl. Basiclly we add two more props into the class dynamically based on other props.

 

'fromJson' & 'formJsonList' are two static function, which helps to stucture our Lesson instance, in Angualr2 we can use like this:

// Service

@Injectable()
export class CourseService {
  lessons$: FirebaseListObservable<Lesson[]>;

  constructor(private rt: RealtimeService) {
    this.lessons$ = rt.getLessonObs();
  }

  getLessons() {
    return this.lessons$
      .map(Lesson.fromJsonList);
  }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
在vscode上运行typescript文件发布时间:2022-07-18
下一篇:
javascript/TypeScript生成GUID发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap