/*
Extract je utility typ v TypeScriptu, který umožňuje vytvořit nový typ extrahováním (vybráním) hodnot, které jsou společné mezi dvěma typy. Funguje jako opak Exclude, protože místo odstranění hodnot vybírá ty, které se shodují. Syntaxe vypadá takto:
Extract<T, U>
*/
// 1
type Status = 'active' | 'inactive' | 'pending' | 'deleted';
type ActiveStatus = Extract<Status, 'active' | 'pending'>;
let status1: ActiveStatus = 'active'; // OK
let status2: ActiveStatus = 'pending'; // OK
let status3: ActiveStatus = 'inactive'; // Error: Type '"inactive"' is not assignable to type 'ActiveStatus'.
// 2
type Numeric = number | string | boolean;
type OnlyString = Extract<Numeric, string>;
const value1: OnlyString = 'Hello'; // OK
const value2: OnlyString = 42; // Error: Type 'number' is not assignable to type 'OnlyString'.
/*
Exclude<T, K>
Exclude je utility typ v TypeScriptu, který umožňuje vytvořit nový typ odstraněním určitých hodnot z existujícího typu. Tento typ pracuje především s tzv. union typy (sjednocení). Jeho syntaxe vypadá takto:
*/
// 1
type Status = 'active' | 'inactive' | 'pending' | 'deleted';
type VisibleStatus = Exclude<Status, 'deleted'>;
let status1: VisibleStatus = 'active'; // OK
let status2: VisibleStatus = 'inactive'; // OK
let status3: VisibleStatus = 'deleted'; // Error: Type '"deleted"' is not assignable to type 'VisibleStatus'.
// 2
type StringOrNull = string | null | undefined;
type StringOnly = Exclude<StringOrNull, null | undefined>;
const value1: StringOnly = 'Hello'; // OK
const value2: StringOnly = null; // Error: Type 'null' is not assignable to type 'StringOnly'.
const value3: StringOnly = undefined; // Error: Type 'undefined' is not assignable to type 'StringOnly'.
/*
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',
};
/*
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.
/*
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',
};
// 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));
/*
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',
};
/*
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 },
};
/*
Demo: https://jsbin.com/hugodahuge/1/edit?html,css,output
*/
.grid {
display: grid;
grid-template-rows: repeat(4, 1fr);
grid-auto-columns: calc((100vh - 3em) / 4);
grid-auto-flow: column;
grid-gap: 1em;
height: 100vh;
}
.grid-item:nth-child(3n) {
background-color: gray;
}
.grid-item:nth-child(3n + 1) {
background-color: green;
}
.grid-item:nth-child(3n + 2) {
background-color: yellow;
}
// https://blog.stackademic.com/how-to-optimize-complex-conditionals-in-javascript-0fcaf0add82a
const onButtonClick = (status) => {
if (status == 1) {
jumpTo('Index Page');
} else if (status == 2 || status == 3) {
jumpTo('Failure Page');
} else if (status == 4) {
jumpTo('Success Page');
} else if (status == 5) {
jumpTo('Cancel Page');
} else {
jumpTo('Other Actions');
}
};
// 1
// if => switch
const onButtonClick = (status) => {
switch (status) {
case 1:
jumpTo('Index Page');
break;
case 2:
case 3:
jumpTo('Failure Page');
break;
case 4:
jumpTo('Success Page');
break;
case 5:
jumpTo('Cancel Page');
break;
default:
jumpTo('Other Actions');
}
};
// ------------------------------------------
const onButtonClick = (status, identity) => {
if (identity == 'guest') {
if (status == 1) {
// logic for guest status 1
} else if (status == 2) {
// logic for guest status 2
}
// Additional logic for other statuses...
} else if (identity == 'master') {
if (status == 1) {
// logic for master status 1
}
// Additional logic for other statuses...
}
};
// 2
// interesting solution ;)
// nested if to map with keys where key mean concaten ifs..
const actions = new Map([
['guest_1', () => { /* logic for guest status 1 */ }],
['guest_2', () => { /* logic for guest status 2 */ }],
['master_1', () => { /* logic for master status 1 */ }],
['master_2', () => { /* logic for master status 2 */ }],
['default', () => { /* default logic */ }],
]);
const onButtonClick = (identity, status) => {
const action = actions.get(`${identity}_${status}`) || actions.get('default');
action();
};
// 3
// object with keys instead of use of ifs
const actions = {
'1': 'Index Page',
'2': 'Failure Page',
'3': 'Failure Page',
'4': 'Success Page',
'5': 'Cancel Page',
'default': 'Other Actions',
};
const onButtonClick = (status) => {
const action = actions[status] || actions['default'];
jumpTo(action);
};