/ Gists / Typescript

Gists - Typescript

On gists

Utility type: Omit

Typescript

index.ts #

/*
Omit je utility typ v TypeScriptu, který umožňuje vytvořit nový typ s vynechanými (omitted) klíči z původního typu. To znamená, že nový typ bude obsahovat všechny vlastnosti z původního typu kromě těch, 
které explicitně specifikujete k vynechání

Omit<T, K>
*/

// 1
interface User {
    id: number;
    name: string;
    email: string;
    password: string;
}

type PublicUser = Omit<User, 'password'>; // nebo Omit<User, 'password' | 'id'>

const user: PublicUser = {
    id: 1,
    name: 'Alice',
    email: 'alice@example.com',
};

On gists

Utility type: Readonly

Typescript

index.ts #

/*
Readonly je utility typ v TypeScriptu, 
který změní všechny vlastnosti daného typu na pouze pro čtení (readonly)

Readonly<T>
*/

// 1
interface User {
    id: number;
    name: string;
    email: string;
}

const user: Readonly<User> = {
    id: 1,
    name: 'Alice',
    email: 'alice@example.com',
};

// Pokus o změnu vlastnosti způsobí chybu
user.name = 'Bob'; // Error: Cannot assign to 'name' because it is a read-only property.

// 2
interface Config {
    apiEndpoint: string;
    timeout: number;
}

const config: Readonly<Config> = {
    apiEndpoint: 'https://api.example.com',
    timeout: 3000,
};

// Tento pokus o úpravu způsobí chybu:
config.timeout = 5000; // Error: Cannot assign to 'timeout' because it is a read-only property.

On gists

Utility type: Required

Typescript

index.ts #

/*
Required je utility typ v TypeScriptu, který změní všechny vlastnosti daného typu na povinné (required).
*/

interface User1 {
    id: number;
    name?: string;
    email?: string;
}

type RequiredUser = Required<User1>;

const user1: RequiredUser = {
    id: 1,
    name: 'Alice',
    email: 'alice@example.com',
};

On gists

Utility type: Partial

Typescript

index.ts #

// union
type StringOrNumber = string | number;

// intersection
type User = { id: number };
type Admin = { isAdmin: boolean };
type AdminUser = User & Admin; // { id: number; isAdmin: boolean; }

// return type
type GetUserType = () => { id: number; name: string };
type UserType = ReturnType<GetUserType>; // { id: number; name: string }

// return type pres interface
interface StringFormat {
    (str: string, isUpper: boolean): string;
}

let format: StringFormat;

format = function (str: string, isUpper: boolean) {
    return isUpper ? str.toLocaleUpperCase() : str.toLocaleLowerCase();
};

console.log(format('hi', true));

On gists

Utility type: Pick

Typescript

index.ts #

/*
Pick:

Pick<T, K> je utility typ v TypeScriptu, který vytváří nový typ výběrem určitých vlastností K z typu T.
Používá se pro vytvoření podmnožiny existujícího typu.
*/

// 1
interface User {
    id: number;
    name: string;
    email: string;
    phone: number;
}

type UserInfo = Pick<User, 'id' | 'name'>;
type UserBasicInfo = Pick<User, 'name' | 'email'>;

const user: UserInfo = {
    id: 1,
    name: 'abc',
};

const userDetails: UserBasicInfo = {
    name: 'abc',
    email: 'abc@gmail.com',
};

interface TestedPerson {
    name: string;
    age: number;
    address: string;
    email: string;
    phone: string;
}

// 2 Kombinace Pick s jinými utility typy
type OptionalPersonBasicInfo = Partial<Pick<TestedPerson, 'name' | 'age'>>;

const partialBasicInfo: OptionalPersonBasicInfo = {
    name: 'Bob',
    // age může být vynecháno
};

// 3 Použití Pick s vnořenými objekty
interface ComplexPerson {
    name: string;
    age: number;
    address: {
        street: string;
        city: string;
        country: string;
    };
}

type PersonNameAndCity = Pick<ComplexPerson, 'name'> & Pick<ComplexPerson['address'], 'city'>;

const nameAndCity: PersonNameAndCity = {
    name: 'Charlie',
    city: 'New York',
};

On gists

Utility type: Record

Typescript

index.ts #

/*
Record<Keys, Type>
Keys může být string, number, symbol nebo union těchto typů.
Type může být jakýkoli typ.

Kdy Record využít
Když chcete zajistit, aby objekt měl přesnou strukturu s předem definovanými typy klíčů a hodnot.
Pokud například potřebujete typově bezpečně definovat mapování mezi hodnotami (např. slovníky nebo konfigurace).
*/

const scores: Record<string, number> = {
    Alice: 10,
    Bob: 20,
    Charlie: 30,
};

type Person = 'name' | 'age' | 'email';
const personInfo: Record<Person, string> = {
    name: 'Alice',
    age: '30',
    email: 'alice@example.com',
};

type Task = {
    title: string;
    completed: boolean;
};
type ProjectTasks = Record<string, Task>;
const projectStatus: ProjectTasks = {
    'Task 1': { title: 'Design UI', completed: true },
    'Task 2': { title: 'Implement backend', completed: false },
    'Task 3': { title: 'Write tests', completed: false },
};