Last active
March 26, 2020 00:47
-
-
Save gmotzespina/f495951c509e4c1108c1d81f97fb3b76 to your computer and use it in GitHub Desktop.
Generics Introduction: Class and interface using generics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export interface StudentProps { | |
| id: number; | |
| name: string; | |
| } | |
| export interface TeacherProps { | |
| id: number; | |
| name: string; | |
| isGoodTeacher: boolean; | |
| } | |
| export class Attributes<T> { | |
| constructor(private data: T) {} | |
| get<K extends keyof T>(key: K): T[K] { | |
| return this.data[key]; | |
| } | |
| set(update: T): void { | |
| this.data = {...this.data, update} | |
| } | |
| } | |
| const studentAttributes = new Attributes<StudentProps>({id: 1, name: 'Ragnar'}); | |
| const studentName = studentAttributes.get('name'); | |
| console.log(typeof studentName); // prints string | |
| const teacherAttributes = new Attributes<TeacherProps>({id: 1, name: 'Lagertha', isGoodTeacher: true}); | |
| const isGoodTeacher = teacherAttributes.get('isGoodTeacher'); | |
| console.log(typeof isGoodTeacher); // prints boolean | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment