Last active
April 21, 2025 19:44
-
-
Save alexkonst/a158a7fc2d6584689e821127d44b5ea6 to your computer and use it in GitHub Desktop.
TS homework 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type User = { | |
id: number | |
name: string | |
email?: string | |
} | |
type UserDict = { | |
[key: User['id']]: User | |
} | |
function getUserEmail(id: number, users: UserDict): string | undefined { | |
return users[id]?.email | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface User { | |
id: number | |
name: string | |
} | |
interface User { | |
email?: string | |
logIn(): void | |
} | |
const user: User = { | |
id: 123, | |
name: 'test', | |
logIn() {} | |
} | |
function printUser(user: User): void { | |
console.log(`id: ${user.id}, name: ${user.name}, email: ${user.email ?? 'n/a'}`) | |
user.logIn() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Shape { | |
color: string | |
area(): number | |
} | |
interface Circle extends Shape { | |
radius: number | |
} | |
interface Rectangle extends Shape { | |
width: number | |
height: number | |
} | |
function createCircle(radius: number): Circle { | |
return { | |
color: 'red', | |
area: () => Math.PI * Math.pow(this.radius, 2), | |
radius | |
} | |
} | |
function createRectangle(width: number, height: number): Rectangle { | |
return { | |
color: 'red', | |
area: () => this.width * this.height, | |
width, | |
height | |
} | |
} | |
function calcArea(shape: Shape): number { | |
return shape.area() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface User { | |
data: { | |
name: string | |
age: number | |
} | |
get name(): User['data']['name'] | |
get age(): User['data']['age'] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum UserRole { | |
Admin = 'Admin', | |
Editor = 'Editor', | |
Viewer = 'Viewer' | |
} | |
enum AccountStatus { | |
Active = 'Active', | |
Suspended = 'Suspended', | |
Banned = 'Banned' | |
} | |
const AllRolesAndStatuses = { | |
...UserRole, | |
...AccountStatus | |
} as const | |
type RoleOrStatus = keyof typeof AllRolesAndStatuses | |
function getAccessLevel(value: RoleOrStatus): string { | |
switch (value) { | |
case UserRole.Admin: | |
case AccountStatus.Active: { | |
return 'Full access' | |
} | |
case UserRole.Editor: { | |
return 'Limited access' | |
} | |
case UserRole.Viewer: | |
case AccountStatus.Suspended: | |
case AccountStatus.Banned: { | |
return 'No access' | |
} | |
default: { | |
return '' | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const enum UserRole { | |
Admin = 'Admin', | |
Editor = 'Editor', | |
Viewer = 'Viewer' | |
} | |
const enum AccountStatus { | |
Active = 'Active', | |
Suspended = 'Suspended', | |
Banned = 'Banned' | |
} | |
function checkPermission(role: UserRole, status: AccountStatus): boolean { | |
return role !== UserRole.Viewer && status !== AccountStatus.Banned | |
} | |
// При использовании `const enum ...` в итоговом js коде отсутствует | |
// сгенерированный код перечислений, а значения из enum инлайнятся в месте использования |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Coordinates = [latitude: number, longitude: number, ...landmarks: string[]] | |
// Возвращает строку: | |
// "Широта: {lat}, Долгота: {lon}. Ориентиры: {landmarks.join(', ')}" | |
// Если ориентиров нет, выводит только координаты | |
function describeLocation(coords: Coordinates): string { | |
const [lat, lon, ...landmarks] = coords | |
let result = `Широта: ${lat}, Долгота: ${lon}.` | |
if (landmarks.length > 0) { | |
result += ` Ориентиры: ${landmarks.join(', ')}.` | |
} | |
return result | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Person = [name: string, age: number, email?: string] | |
// Возвращает строку вида "Привет, {name}! Тебе {age} лет." | |
// Если есть email, добавляет " Контакты: {email}" | |
function greet(person: Person): string { | |
const [name, age, email] = person | |
let result = `Привет, ${name}! Тебе ${age} лет.` | |
if (email && email.length > 0) { | |
result += ` Контакты: ${email}.` | |
} | |
return result | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type RGB = readonly [r: number, g: number, b: number] | |
type RGBA = readonly [...rgb: RGB, a?: number] | |
// Возвращает инвертированный цвет (255 - r, 255 - g, 255 - b) | |
function invertColor([r, g, b]: RGB): RGB { | |
return [255 - r, 255 - g, 255 - b] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Status = 'pending' | 'completed' | |
type Order = [id: string, items: string[], status?: Status, ...meta:[string, any][]] | |
// Возвращает строку: | |
// "Заказ #{id}. Товары: {items.join(', ')}. Статус: {status || 'не указан'}" | |
// Если есть метаданные, добавляет их в конец | |
function processOrder(order: Order): string { | |
const [id, items, status, ...meta] = order | |
let result = `Заказ #${id}. Товары: ${items.join(', ')}. Статус: ${status || 'не указан'}.` | |
if (meta.length > 0) { | |
result += ' Мета:' | |
for (const [key, value] of meta) { | |
result += ` ${key}: ${value};` | |
} | |
} | |
return result | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Employee = {id: number, department: string} | |
type Manager = {teamSize: number, role: string} | |
type TeamLead = Employee & Manager | |
const teamLead: TeamLead = { | |
id: 123, | |
department: 'it', | |
teamSize: 20, | |
role: 'lead software engineer' | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function throwError(message: string): never { | |
throw new Error(message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment