Skip to content

Instantly share code, notes, and snippets.

@Neo42
Created January 7, 2022 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Neo42/77785811e403c1723d758adb79d171ad to your computer and use it in GitHub Desktop.
Save Neo42/77785811e403c1723d758adb79d171ad to your computer and use it in GitHub Desktop.
Generics are to types as functions are to values.
function getFirstItem<Type>(list: Type[]): Type {
return list[0]
}
const item = getFirstItem([1])
const item2 = getFirstItem([''])
const item3 = getFirstItem([new Object()])
type Tree<Type> = {
value: Type
left?: Tree<Type>
right?: Tree<Type>
}
interface Ball {
name: string
color: string
}
const ballTree: Tree<Ball> = {
value: {name: 'basketball', color: 'orange'},
left: {value: {name: 'football', color: 'white'}},
}
class Basket<Type> {
constructor(public things: Type[]) {}
add(thing: Type) {
this.things.push(thing)
}
eat() {
this.things.pop()
}
}
class Fruit {
isFruit: true
constructor(public name: string) {}
}
class Apple extends Fruit {
type: 'Apple'
constructor() {
super('Apple')
}
}
class Banana extends Fruit {
type: 'Banana'
constructor() {
super('Banana')
}
}
class Vegetable {
isFruit: false
constructor(public name: string) {}
}
class Cucumber extends Vegetable {
type: 'Cucumber'
constructor() {
super('Cucumber')
}
}
const fruitBasket = new Basket<Fruit>([])
fruitBasket.add(new Apple())
const appleBasket = new Basket<Apple>([])
appleBasket.add(new Apple())
const bananaBasket = new Basket<Banana>([])
bananaBasket.add(new Banana())
const vegetableBasket = new Basket<Vegetable>([new Cucumber()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment