# TypeScript домашние задания

**URL:** <https://forum.itvdn.com/t/typescript-domashnie-zadaniya/3436>\
**Category:** Frontend developer\
**Created:** [27.09.2019 18:16:23 UTC](https://forum.itvdn.com/t/typescript-domashnie-zadaniya/3436 "2019-09-27T18:16:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![HOG](https://forum.itvdn.com/user_avatar/forum.itvdn.com/hog/32/354_2.png) [@HOG](https://forum.itvdn.com/u/HOG)\
**Post date:** [27.09.2019 18:16:24 UTC](https://forum.itvdn.com/t/typescript-domashnie-zadaniya/3436/1 "2019-09-27T18:16:24Z")

</div>

Я не нашёл примеры домашних заданий по курсу TypeScript Fundamentals и проверка их ментором недоступна. Хотелось бы получить обратную связь по решению таких заданий.

---

<div class="post-metadata">

**Author:** ![HOG](https://forum.itvdn.com/user_avatar/forum.itvdn.com/hog/32/354_2.png) [@HOG](https://forum.itvdn.com/u/HOG)\
**Post date:** [27.09.2019 18:20:03 UTC](https://forum.itvdn.com/t/typescript-domashnie-zadaniya/3436/2 "2019-09-27T18:20:03Z")

</div>

Урок 1. Типы данных и функции

Задание:  
Используя TS, создайте следующую функцию, рассчитывающую стоимость мороженого:  
Магазин предлагает 2 размера мороженого:  
 Маленький стакан (10грн)  
 Большой стакан (25грн). Мороженое дополняется одной или несколькими начинками (минимум -  
одной):  
-шоколад (+5грн);  
-карамель (+6грн);  
-ягоды (+10грн).  
Дополнительно (не обязательно) мороженое можно посыпать маршмеллоу (+5грн).  
Входящие параметры пользователь вводит через prompt.

Моё решение:

```
const icecream = {

```

'small': {  
'price': 10  
},  
'big': {  
'price': 25,  
'toppings': {  
'chocolate': 5,  
'caramel': 6,  
'berry': 10  
}  
},  
'marmalow': {  
'price': 5  
}

};  
let buyIcecream = () : void =\> {  
let price: number = 0;  
let type: string = prompt ('Ice cream type?', 'small');  
switch(type) {  
case 'small':  
price = price + icecream.small.price;  
break;  
case 'big':  
price = price + icecream.big.price + choseToppings();  
break;  
}  
let marmalow: string = prompt ('Do you need marmalow?');  
if (marmalow == 'yes') {  
price = price + icecream.marmalow.price;  
}  
alert(`Ice cream price" ${price}`);  
};

let choseToppings = () : number =\> {  
let toppingsPrice: number = 0;  
let toppingsList : string = prompt('Choose toppings. Available: chocolate, caramel, berry.', 'chocolate');

let countToppingPrice = () =\> {  
let toppingsArr = toppingsList.split(', ');  
for(let i = 0; i \< toppingsArr.length; i++) {  
switch(toppingsArr[i]) {  
case 'chocolate':  
toppingsPrice = toppingsPrice + icecream.big.toppings.chocolate;  
break;  
case 'caramel':  
toppingsPrice = toppingsPrice + icecream.big.toppings.caramel;  
break;  
case 'berry':  
toppingsPrice = toppingsPrice + icecream.big.toppings.berry;  
break;  
default:  
validateToppingsList();  
break;  
}  
}  
};

let validateToppingsList = () =\> {  
toppingsList = prompt('You must choose one of toppings. Available: chocolate, caramel, berry.', 'chocolate');  
countToppingPrice();  
};

if (toppingsList == undefined) {  
validateToppingsList();  
}  
else {  
countToppingPrice();  
}

return toppingsPrice;  
};

buyIcecream();

---

<div class="post-metadata">

**Author:** ![HOG](https://forum.itvdn.com/user_avatar/forum.itvdn.com/hog/32/354_2.png) [@HOG](https://forum.itvdn.com/u/HOG)\
**Post date:** [01.10.2019 16:53:27 UTC](https://forum.itvdn.com/t/typescript-domashnie-zadaniya/3436/3 "2019-10-01T16:53:27Z")

</div>

Урок 2:

2.1 - Создайте интерфейс, описывающий поведение животного (свойства, методы передвижения). Примените данный интерфейс к классу Cat, Bird, Fish. Подумайте, какие свойства должны быть опциональными.

2.2 - Создать понятие абстрактного родительского класса Car. От него создать 3 производных класса (марки автомобилей) с применением метода super(). В классах использовать модификаторы как в родительском классе, так и в производных. Создать от производных классов минимум по 2 экземпляра (модели автомобилей). Методы в производных классах должны выводить на экран все свойства (описание автомобиля). Подумайте, какие свойства в производных классах должны быть public, какие – private и protected.

2.1:

interface Animal {  
moving: string;  
voice?: string;  
info: () =\> string;  
}

class Cat implements Animal {  
moving: string;  
voice: string;

constructor (moving:string, voice?: string) {  
this.moving = moving;  
this.voice = voice;  
}

info () : string {  
return `This animal: moving in the ${this.moving}, say: ${this.voice}.`;  
}  
}

class Bird implements Animal {  
moving: string = 'air';  
voice: string = 'piu';

info () : string {  
return `This animal: moving in the ${this.moving}, say: ${this.voice}.`;  
}  
}

class Fish implements Animal {  
moving: string = 'water';

info () : string {  
return `This animal: moving in the ${this.moving}.`;  
}  
}  
let animal = new Cat('land', 'miau').info();  
console.log(animal);  
console.log(new Bird().info());  
console.log(new Fish().info());

2.2

abstract class Car {  
protected country: string;

constructor (private brand: string) {}

public getInfo() : string {  
return this.brand;  
}  
}

class Opel extends Car {  
type: string;

constructor(country: string, type: string) {  
super('Opel');  
this.country = country;  
this.type = type;  
}

public getInfo () : string {  
let mainInfo: string = super.getInfo();  
return `Car information: ${mainInfo}, ${this.country}, ${this.type}`;  
}  
}

class Bmw extends Car {  
year: number;

constructor (country: string, year: Date) {  
super('Bmw');  
this.country = country;  
this.year = year.getFullYear();  
}

public getInfo () : string {  
let mainInfo: string = super.getInfo();  
return `Car information: ${mainInfo}, ${this.country}, ${this.year}`;  
}  
}

class Ford extends Car {  
vin: number;

constructor (country: string, vin: number) {  
super('Ford');  
this.country = country;  
this.vin = vin;  
}

public getInfo () : string {  
let mainInfo: string = super.getInfo();  
return `Car information: ${mainInfo}, ${this.country}, ${this.vin}`;  
}  
}

let cars: Car[] = [];

cars.push(new Opel('Germany', 'Lorry'));  
cars.push(new Bmw('Germany', new Date('1985-01-01')));  
cars.push(new Ford('USA', 7987897983987));  
cars.push(new Opel('Ukraine', 'Sedan'));  
cars.push(new Bmw('Poland', new Date('1991-01-01')));  
cars.push(new Ford('France', 898098));

for (let i = 0; i \< cars.length; ++i) {  
console.log(cars[i].getInfo());  
}
