[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); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具