Created
January 7, 2022 16:53
-
-
Save Neo42/77785811e403c1723d758adb79d171ad to your computer and use it in GitHub Desktop.
Generics are to types as functions are to values.
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
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