Skip to content

Instantly share code, notes, and snippets.

@gmotzespina
Last active March 26, 2020 00:47
Show Gist options
  • Select an option

  • Save gmotzespina/f495951c509e4c1108c1d81f97fb3b76 to your computer and use it in GitHub Desktop.

Select an option

Save gmotzespina/f495951c509e4c1108c1d81f97fb3b76 to your computer and use it in GitHub Desktop.
Generics Introduction: Class and interface using generics
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