Last active
March 26, 2019 01:58
-
-
Save micahriggan/e748eae5febb13633703954c37404fa7 to your computer and use it in GitHub Desktop.
A typesafe example using generics
This file contains 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
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