Skip to content

Instantly share code, notes, and snippets.

@micahriggan
Last active March 26, 2019 01:58
Show Gist options
  • Save micahriggan/e748eae5febb13633703954c37404fa7 to your computer and use it in GitHub Desktop.
Save micahriggan/e748eae5febb13633703954c37404fa7 to your computer and use it in GitHub Desktop.
A typesafe example using generics
interface Person {
name: string;
age: number;
}
interface Car {
modelName: string;
year: number;
}
// Allow Table to use any type, and call it RowType
class Table<RowType> {
rows = new Array<RowType>();
addRow(row: RowType) {
this.rows.push(row);
}
getColumn(col: keyof RowType) {
return this.rows.map(r => r[col]);
}
}
function testTable() {
const people = new Table<Person>()
//people.addRow({name: 'Micah'});
people.addRow({name: 'Micah', age: 25});
const cars = new Table<Car>();
cars.addRow({modelName: 'Toyota Something or Other', year: 2010});
//cars.addRow({modelNme: 'Honda Something or Other', year: 2010});
cars.getColumn("modelName");
cars.getColumn("year");
//cars.getColumn("age");
}
testTable();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment