Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 20 additions & 16 deletions src/task_1/index.ts
Original file line number Diff line number Diff line change
@@ -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<number | Date>,
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);
42 changes: 33 additions & 9 deletions src/task_2/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
/** Задача 2
* Требуется реализовать функцию filter, которая будет принимать
* массив с объектами 3х типов
* наименование типа
* возврщать массив с объектами, которые имеют тип, указанный во втором аргументе
*/

enum System {
Linux = 0,
Window = 1,
Expand All @@ -26,7 +19,7 @@ type ThirdType = {
prop2: boolean,
prop3: System,
}

const obj1: FirstType = {
prop1: "Привет, РТФ!",
prop2: false,
Expand Down Expand Up @@ -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<FirstType | SecondType | ThirdType>, type: string) {
let res: Array<FirstType | SecondType | ThirdType> = [];
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');

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 балл

15 changes: 3 additions & 12 deletions src/task_3/index.ts
Original file line number Diff line number Diff line change
@@ -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
function add(x: string | number, y: string | number): string | number {
return typeof x === "string" ? <string>x + <string>y : <number>x + <number>y;
}
7 changes: 1 addition & 6 deletions src/task_4/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
/** Задача 4
* Разобраться и описать в чём заключается разница между IFoo и FooType
* (фактически нужно описать в чём разница между type и interface)
* + к карме, если приведете примеры
*/
interface IFoo {
a: number
b: string
}

type FooType = {
a: number
b: string
Expand Down
33 changes: 14 additions & 19 deletions src/task_5/index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
/** Задача 4
* Измените объявление функции filterUsers так, чтобы
* в аргумент criteria можно было передавать объект,
* содержащий любое поле или поля объекта User
*/

interface User {
type: string;
name: string;
age: number;
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',
Expand Down Expand Up @@ -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)) {
Expand All @@ -73,20 +70,18 @@ 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) => {
return user[fieldName] === criteria[fieldName];
});
});
}

console.log('Users of age 23:');

filterUsers(
persons,
{
age: 23
}
).forEach(logPerson);
).forEach(logPerson);