From 4a335523eb60b4eeb66f1795d44985de3c5df43e Mon Sep 17 00:00:00 2001 From: diukin9 Date: Sun, 23 May 2021 19:12:29 +0500 Subject: [PATCH] =?UTF-8?q?=D0=94=D1=8E=D0=BA=D0=B8=D0=BD=20=D0=9F=D0=B5?= =?UTF-8?q?=D1=82=D1=80=20//=20ts-1=20//=20=D0=9F=D0=B5=D1=80=D0=B5=D0=B7?= =?UTF-8?q?=D0=B0=D0=BB=D0=B8=D0=B2=20=D0=92=D0=A2=D0=9E=D0=A0=D0=9E=D0=93?= =?UTF-8?q?=D0=9E(!)=20=D0=BD=D0=BE=D0=BC=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/task_1/index.ts | 36 ++++++++++++++++++++---------------- src/task_2/index.ts | 42 +++++++++++++++++++++++++++++++++--------- src/task_3/index.ts | 15 +++------------ src/task_4/index.ts | 7 +------ src/task_5/index.ts | 33 ++++++++++++++------------------- 5 files changed, 71 insertions(+), 62 deletions(-) diff --git a/src/task_1/index.ts b/src/task_1/index.ts index 3edb7b9..b4c1c01 100644 --- a/src/task_1/index.ts +++ b/src/task_1/index.ts @@ -1,38 +1,42 @@ - /** Задача 1 - * Требуется описать типы FooType и BarType так, чтобы код, - * который написан в функции logObj компилировался и исполнялся корректно -*/ +type FooType = { + stringProp: string, + numberProp: number, + barObject: BarType, +}; -type FooType = unknown; -type BarType = unknown; +type BarType = { + stringsArrayProp: string[], + numbersOrDatesArrayProp: Array, + functionProp: Function +}; export const fooObjects: FooType[] = [ { stringProp: 'firstFoo', numberProp: 2077, barObject: { - stringsArrayProp: ['barString1', 'barString2', 'barString3'], - numbersOrDatesArrayProp: [new Date(), 100500, new Date(2077), 2020], - functionProp: (flag: boolean) => console.log(!flag), - } + stringsArrayProp: ['barString1', 'barString2', 'barString3'], + numbersOrDatesArrayProp: [new Date(), 100500, new Date(2077), 2020], + functionProp: (flag: boolean) => console.log(!flag), + } }, { stringProp: 'secondFoo', numberProp: 2020, barObject: { - stringsArrayProp: ['barString1', 'barString2', 'barString3'], - numbersOrDatesArrayProp: [new Date(2077), 2020, new Date(), 100500], - functionProp: (flag: boolean) => console.log(flag), - } + stringsArrayProp: ['barString1', 'barString2', 'barString3'], + numbersOrDatesArrayProp: [new Date(2077), 2020, new Date(), 100500], + functionProp: (flag: boolean) => console.log(flag), + } }, ]; function logObj(fooObject: FooType) { console.log(`stringProp -- ${fooObject.stringProp}`); - console.log(`numberProp -- ${fooObject.numberProp}`) + console.log(`numberProp -- ${fooObject.numberProp}`) console.log(`barObject.stringsArrayProp -- ${fooObject.barObject.stringsArrayProp}`) console.log(`barObject.numbersOrDatesArrayProp -- ${fooObject.barObject.numbersOrDatesArrayProp}`) console.log(`barObject.functionProp -- ${fooObject.barObject.functionProp(true)}`) } - + fooObjects.forEach(logObj); \ No newline at end of file diff --git a/src/task_2/index.ts b/src/task_2/index.ts index 00b4939..a5ca20c 100644 --- a/src/task_2/index.ts +++ b/src/task_2/index.ts @@ -1,10 +1,3 @@ -/** Задача 2 - * Требуется реализовать функцию filter, которая будет принимать - * массив с объектами 3х типов - * наименование типа - * возврщать массив с объектами, которые имеют тип, указанный во втором аргументе -*/ - enum System { Linux = 0, Window = 1, @@ -26,7 +19,7 @@ type ThirdType = { prop2: boolean, prop3: System, } - + const obj1: FirstType = { prop1: "Привет, РТФ!", prop2: false, @@ -70,9 +63,40 @@ const obj7: ThirdType = { const array = [obj1, obj2, obj3, obj4, obj5, obj6, obj7]; +function isFirstType(obj : FirstType | SecondType | ThirdType) { + return typeof obj.prop2 === "boolean" && !("prop3" in obj); +} + +function isSecondType(obj : FirstType | SecondType | ThirdType) { + return typeof obj.prop2 === "function"; +} + +function isThirdType(obj : FirstType | SecondType | ThirdType) { + return "prop3" in obj; +} + function filter(array: Array, type: string) { + let res: Array = []; + switch (type) { + case "FirstType": + array.forEach(x => { + if (isFirstType(x)) res.push(x); + }); + break; + case "SecondType": + array.forEach(x => { + if (isSecondType(x)) res.push(x); + }); + break; + case "ThirdType": + array.forEach(x => { + if (isThirdType(x)) res.push(x); + }); + break; + } + return res; } filter(array, 'FirstType'); filter(array, 'SecondType'); -filter(array, 'ThirdType'); +filter(array, 'ThirdType'); \ No newline at end of file diff --git a/src/task_3/index.ts b/src/task_3/index.ts index b7c9cdc..dfb746e 100644 --- a/src/task_3/index.ts +++ b/src/task_3/index.ts @@ -1,12 +1,3 @@ -/** Задача 3 - * Требуется реализовать функцию add, которая будет иметь 2 сигнатуры - * 1 - принимает 2 аргумента: x, y оба типа string и возвращает тип string - * 2 - принимает 2 аргумента: x, y оба типа number и возвращает тип number - * использовать тип any для типизации параметров запрещено - * функция должна возвращать сумму двух аргументов -*/ -function add(x: string, y: string): string; -function add(x: number, y: number): number; - -add('20', '21'); //2021 -add(20, 21); //41 \ No newline at end of file +function add(x: string | number, y: string | number): string | number { + return typeof x === "string" ? x + y : x + y; +} \ No newline at end of file diff --git a/src/task_4/index.ts b/src/task_4/index.ts index e884df8..3c1f3be 100644 --- a/src/task_4/index.ts +++ b/src/task_4/index.ts @@ -1,13 +1,8 @@ -/** Задача 4 - * Разобраться и описать в чём заключается разница между IFoo и FooType - * (фактически нужно описать в чём разница между type и interface) - * + к карме, если приведете примеры -*/ interface IFoo { a: number b: string } - + type FooType = { a: number b: string diff --git a/src/task_5/index.ts b/src/task_5/index.ts index ef3e0c0..4b5ff40 100644 --- a/src/task_5/index.ts +++ b/src/task_5/index.ts @@ -1,9 +1,3 @@ -/** Задача 4 - * Измените объявление функции filterUsers так, чтобы - * в аргумент criteria можно было передавать объект, - * содержащий любое поле или поля объекта User -*/ - interface User { type: string; name: string; @@ -11,22 +5,27 @@ interface User { occupation: string; } +interface HybridUser { + type?: string; + name?: string; + age?: number; + occupation?: string; +} + interface Admin { type: string; name: string; age: number; role: string; } - export type Person = User | Admin; - export const persons: Person[] = [ { - type: 'user', - name: 'Max Mustermann', - age: 25, - occupation: 'Chimney sweep' - }, + type: 'user', + name: 'Max Mustermann', + age: 25, + occupation: 'Chimney sweep' + }, { type: 'admin', name: 'Jane Doe', @@ -58,10 +57,8 @@ export const persons: Person[] = [ role: 'Administrator' } ]; - export const isAdmin = (person: Person): person is Admin => person.type === 'admin'; export const isUser = (person: Person): person is User => person.type === 'user'; - export function logPerson(person: Person) { let additionalInformation = ''; if (isAdmin(person)) { @@ -73,7 +70,7 @@ export function logPerson(person: Person) { console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`); } -export function filterUsers(persons: Person[], criteria: User): User[] { +export function filterUsers(persons: Person[], criteria: HybridUser): User[] { return persons.filter(isUser).filter((user) => { const criteriaKeys = Object.keys(criteria); return criteriaKeys.every((fieldName) => { @@ -81,12 +78,10 @@ export function filterUsers(persons: Person[], criteria: User): User[] { }); }); } - console.log('Users of age 23:'); - filterUsers( persons, { age: 23 } -).forEach(logPerson); \ No newline at end of file +).forEach(logPerson);