首页 > 代码库 > [TypeScript] Interface and Class
[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); }}
[TypeScript] Interface and Class
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。