Skip to content

Instantly share code, notes, and snippets.

@alexkonst
Last active April 21, 2025 19:44
Show Gist options
  • Save alexkonst/a158a7fc2d6584689e821127d44b5ea6 to your computer and use it in GitHub Desktop.
Save alexkonst/a158a7fc2d6584689e821127d44b5ea6 to your computer and use it in GitHub Desktop.
TS homework 3
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
}
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()
}
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()
}
interface User {
data: {
name: string
age: number
}
get name(): User['data']['name']
get age(): User['data']['age']
}
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 ''
}
}
}
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 инлайнятся в месте использования
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
}
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
}
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]
}
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
}
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'
}
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