From f680473c8c250a282a4ae18f726893d5f183b997 Mon Sep 17 00:00:00 2001 From: Mikhail Bobrov Date: Wed, 3 Nov 2021 11:57:13 +0500 Subject: [PATCH] ts-task-1 --- src/task_1/index.ts | 69 +++++++++++++--------- src/task_2/index.ts | 100 +++++++++++++++++++------------- src/task_3/index.ts | 16 +++-- src/task_4/index.ts | 121 ++++++++++++++++++++++++++++++++++++-- src/task_5/index.ts | 138 ++++++++++++++++++++++---------------------- 5 files changed, 299 insertions(+), 145 deletions(-) diff --git a/src/task_1/index.ts b/src/task_1/index.ts index 3edb7b9..358bbce 100644 --- a/src/task_1/index.ts +++ b/src/task_1/index.ts @@ -1,38 +1,53 @@ - /** Задача 1 +/** Задача 1 * Требуется описать типы FooType и BarType так, чтобы код, * который написан в функции logObj компилировался и исполнялся корректно -*/ + */ -type FooType = unknown; -type BarType = unknown; +type FooType = { + stringProp: string; + numberProp: number; + barObject: BarType; +}; + +type BarType = { + stringsArrayProp: [string, string, string]; + numbersOrDatesArrayProp: Array; + functionProp: (boolean) => void; +}; 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), - } + { + stringProp: "firstFoo", + numberProp: 2077, + barObject: { + 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), - } + }, + { + stringProp: "secondFoo", + numberProp: 2020, + barObject: { + 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(`barObject.stringsArrayProp -- ${fooObject.barObject.stringsArrayProp}`) - console.log(`barObject.numbersOrDatesArrayProp -- ${fooObject.barObject.numbersOrDatesArrayProp}`) - console.log(`barObject.functionProp -- ${fooObject.barObject.functionProp(true)}`) + console.log(`stringProp -- ${fooObject.stringProp}`); + 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 + +fooObjects.forEach(logObj); diff --git a/src/task_2/index.ts b/src/task_2/index.ts index 00b4939..749c77d 100644 --- a/src/task_2/index.ts +++ b/src/task_2/index.ts @@ -3,76 +3,98 @@ * массив с объектами 3х типов * наименование типа * возврщать массив с объектами, которые имеют тип, указанный во втором аргументе -*/ + */ enum System { - Linux = 0, - Window = 1, - MacOS = 2, + Linux = 0, + Window = 1, + MacOS = 2, } type FirstType = { - prop1: string, - prop2: boolean, -} + prop1: string; + prop2: boolean; +}; type SecondType = { - prop1: typeof undefined, - prop2: () => Date, -} + prop1: typeof undefined; + prop2: () => Date; +}; type ThirdType = { - prop1: string, - prop2: boolean, - prop3: System, -} - + prop1: string; + prop2: boolean; + prop3: System; +}; + const obj1: FirstType = { - prop1: "Привет, РТФ!", - prop2: false, + prop1: "Привет, РТФ!", + prop2: false, }; const obj2: FirstType = { - prop1: "Привет, УрФУ!", - prop2: true, + prop1: "Привет, УрФУ!", + prop2: true, }; const obj3: FirstType = { - prop1: "Привет, мир!", - prop2: true, + prop1: "Привет, мир!", + prop2: true, }; const obj4: SecondType = { - prop1: undefined, - prop2: () => { - return new Date(); - } + prop1: undefined, + prop2: () => { + return new Date(); + }, }; const obj5: SecondType = { - prop1: undefined, - prop2: () => { - return new Date(2021, 3, 1); - } + prop1: undefined, + prop2: () => { + return new Date(2021, 3, 1); + }, }; const obj6: ThirdType = { - prop1: "Cats", - prop2: true, - prop3: System.Linux + prop1: "Cats", + prop2: true, + prop3: System.Linux, }; const obj7: ThirdType = { - prop1: "Dogs", - prop2: true, - prop3: System.MacOS + prop1: "Dogs", + prop2: true, + prop3: System.MacOS, }; const array = [obj1, obj2, obj3, obj4, obj5, obj6, obj7]; -function filter(array: Array, type: string) { +function filter( + array: Array, + type: string +) { + return array.filter((item) => { + if ( + typeof item.prop2 === "boolean" && + typeof item.prop1 === "string" && + type === "FirstType" && + Object.keys(item).length === 2 + ) { + console.log(item); + return item; + } + if (typeof item.prop1 === typeof undefined && type === "SecondType") { + console.log(item); + return item; + } + if (Object.keys(item).length === 3) { + console.log(item); + return item; + } + }); } -filter(array, 'FirstType'); -filter(array, 'SecondType'); -filter(array, 'ThirdType'); +filter(array, "FirstType"); +filter(array, "SecondType"); +filter(array, "ThirdType"); diff --git a/src/task_3/index.ts b/src/task_3/index.ts index b7c9cdc..a76246e 100644 --- a/src/task_3/index.ts +++ b/src/task_3/index.ts @@ -4,9 +4,15 @@ * 2 - принимает 2 аргумента: x, y оба типа number и возвращает тип number * использовать тип any для типизации параметров запрещено * функция должна возвращать сумму двух аргументов -*/ -function add(x: string, y: string): string; -function add(x: number, y: number): number; + */ +function add(x: string, y: string): string { + console.log(x + y); + return x + y; +} +function add1(x: number, y: number): number { + console.log(x + y); + return x + y; +} -add('20', '21'); //2021 -add(20, 21); //41 \ No newline at end of file +add("20", "21"); //2021 +add1(20, 21); //41 diff --git a/src/task_4/index.ts b/src/task_4/index.ts index e884df8..bff59a8 100644 --- a/src/task_4/index.ts +++ b/src/task_4/index.ts @@ -2,13 +2,122 @@ * Разобраться и описать в чём заключается разница между IFoo и FooType * (фактически нужно описать в чём разница между type и interface) * + к карме, если приведете примеры -*/ + */ interface IFoo { - a: number - b: string + a: number; + b: string; } - + type FooType = { - a: number - b: string + a: number; + b: string; }; + +//В отличие от объявления интерфейса, которое всегда представляет именованный тип объекта, применение ключевого слова type позволяет задать псевдоним для любой разновидности типа, включая примитивные типы, типы-объединения и типы-пересечения. + +// При использовании ключевого слова type вместо ключевого слова interface теряются следующие возможности: + +// Интерфейс может быть использован в выражении extends или implements, а псевдоним для литерала объектного типа — нет. +// Интерфейс может иметь несколько объединённых объявлений, а при использовании ключевого слова type эта возможность не доступна. + +// 1 +//Оба могут использоваться для описания формы объекта или сигнатуры функции. Но синтаксис отличается. + +interface Point { + x: number; + y: number; +} + +interface SetPoint { + (x: number, y: number): void; +} + +// type Point = { +// x: number; +// y: number; +// }; + +// type SetPoint = (x: number, y: number) => void; + +// 2 +// В отличие от интерфейса, псевдоним типа также может использоваться для других типов, таких как примитивы, объединения и кортежи. +// primitive +type Name = string; + +// object +type PartialPointX = { x: number }; +type PartialPointY = { y: number }; + +// union +type PartialPoint = PartialPointX | PartialPointY; + +// tuple +type Data = [number, string]; + +// 3 Extend - расширение +// Оба могут быть расширены, но опять же, синтаксис отличается. Кроме того, обратите внимание, что интерфейс и псевдоним типа не исключают друг друга. Интерфейс может расширять псевдоним типа и наоборот. + +// Interface extends interface +interface PartialPointX2 { + x: number; +} +interface Point extends PartialPointX2 { + y: number; +} + +// Type alias extends type alias +type PartialPointX3 = { x: number }; +type Point3 = PartialPointX3 & { y: number }; + +// Interface extends type alias +type PartialPointX4 = { x: number }; +interface Point extends PartialPointX { + y: number; +} + +// Type alias extends interface +interface PartialPointX5 { + x: number; +} +type Point11 = PartialPointX5 & { y: number }; + +// 4 Implements +interface Point { + x: number; + y: number; +} + +class SomePoint implements Point { + x = 1; + y = 2; +} + +type Point2 = { + x: number; + y: number; +}; + +class SomePoint2 implements Point2 { + x = 1; + y = 2; +} + +type PartialPoint2 = { x: number } | { y: number }; + +// FIXME: can not implement a union type +// class SomePartialPoint implements PartialPoint2 { +// x = 1; +// y = 2; +// } + +// 5 Объединение деклараций +// В отличие от псевдонима типа, интерфейс может быть определен несколько раз и будет рассматриваться как единый интерфейс (с объединенными членами всех объявлений). + +interface Point { + x: number; +} +interface Point { + y: number; +} + +const point: Point = { x: 1, y: 2 }; diff --git a/src/task_5/index.ts b/src/task_5/index.ts index ef3e0c0..c9a07a3 100644 --- a/src/task_5/index.ts +++ b/src/task_5/index.ts @@ -2,91 +2,93 @@ * Измените объявление функции filterUsers так, чтобы * в аргумент criteria можно было передавать объект, * содержащий любое поле или поля объекта User -*/ + */ interface User { - type: string; - name: string; - age: number; - occupation: string; + type: string; + name: string; + age: number; + occupation?: string; } interface Admin { - type: string; - name: string; - age: number; - role: string; + 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: 'admin', - name: 'Jane Doe', - age: 32, - role: 'Administrator' - }, - { - type: 'user', - name: 'Kate Müller', - age: 23, - occupation: 'Astronaut' - }, - { - type: 'admin', - name: 'Bruce Willis', - age: 64, - role: 'World saver' - }, - { - type: 'user', - name: 'Wilson', - age: 23, - occupation: 'Ball' - }, - { - type: 'admin', - name: 'Agent Smith', - age: 23, - role: 'Administrator' - } + { + type: "user", + name: "Max Mustermann", + age: 25, + occupation: "Chimney sweep", + }, + { + type: "admin", + name: "Jane Doe", + age: 32, + role: "Administrator", + }, + { + type: "user", + name: "Kate Müller", + age: 23, + occupation: "Astronaut", + }, + { + type: "admin", + name: "Bruce Willis", + age: 64, + role: "World saver", + }, + { + type: "user", + name: "Wilson", + age: 23, + occupation: "Ball", + }, + { + type: "admin", + name: "Agent Smith", + age: 23, + 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 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)) { - additionalInformation = person.role; - } - if (isUser(person)) { - additionalInformation = person.occupation; - } - console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`); + let additionalInformation = ""; + if (isAdmin(person)) { + additionalInformation = person.role; + } + if (isUser(person)) { + additionalInformation = person.occupation; + } + console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`); } -export function filterUsers(persons: Person[], criteria: User): User[] { - return persons.filter(isUser).filter((user) => { - const criteriaKeys = Object.keys(criteria); - return criteriaKeys.every((fieldName) => { - return user[fieldName] === criteria[fieldName]; - }); +export function filterUsers( + persons: Person[], + criteria: Partial +): User[] { + return persons.filter(isUser).filter((user) => { + const criteriaKeys = Object.keys(criteria); + return criteriaKeys.every((fieldName) => { + return user[fieldName] === criteria[fieldName]; }); + }); } -console.log('Users of age 23:'); +console.log("Users of age 23:"); -filterUsers( - persons, - { - age: 23 - } -).forEach(logPerson); \ No newline at end of file +filterUsers(persons, { + age: 23, +}).forEach(logPerson);