[TypeScript] Interface and Class

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

 

转载于:https://www.cnblogs.com/Answer1215/p/5935369.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值