Classes and Inheritance (TypeScript) - PintoGideon/Recursive-React-Tree-Component GitHub Wiki
function Pizza(name:string){
this.name=name;
this.toppings=[]
}
Pizza.prototype.addTopping=function addToppings(topping:string){
this.toppings.push(topping);
}
const pizza=new Pizza('Pepperoni');
pizza.addToppping('pepperoni');
class Pizza{
name:string;
toppings:string[]=[]
constructor(name:string){
this.name=name; // Property name does not exist on type Pizza
}
addTopping(topping:string){
this.toppings.push(topping);
}
}
const pizza=new Pizza("Pepperoni");
class Sizes {
constructor(size:string[]){}
set availableSizes(sizes:string[]){
this.sizes=sizes
}
get availableSizes(){
return this.sizes;
}
}
class Pizza extends Sizes{
name:string;
constructor(name:string,sizes:string[]){
super(sizes);
this.name=name; // Property name does not exist on type Pizza
}
addTopping(topping:string){
this.toppings.push(topping);
}
}
const pizza=new Pizza('Pepperoni',['small','medium']);
console.log(pizza.availableSizes)
class Pizza {
constructor(private name:string, private price:number){
}
}
class List {
private list: any[];
addItem(item:any):void{
this.list.push(item);
}
getList():any[]{
return this.list
}
}
const list= new List();
list.addItem(new Pizza('Pepperoni',14)); // Array of type Pizza
const pizzas=list.getList();
We can add a placeholder type instead of any
.
class List <T>{
private list:T[]
addItem(item:T):void{
this.list.push(item);
}
getList():T[]{
return this.list;
}
}
const list=new List<Pizza>();
list.addItem(new Pizza('Pepperoni',15));
const pizzas=list.getList();
function reverse(str:string):string;
function reverse<T>(arr:T[]):T[]
function reverse(something:string | any[]):string | any[]{
if(typeof something==='string'){
return something.split('').reverse().join('');
}
return something.slice().reverse();
}
reverse('Pepperoni')
reverse(['bacon','pepperoni','chili','mushrooms'])
// Typescript inference
function reverse<string>(arr:string[]):string[]