PROG_WAY_BLOG Telegram 264
Шпаргалка по Utility-типам в TypeScript

В этом посте разберу только самые часто используемые, посмотреть все utility-типы можно в официальной документации.

type Person = {
name: string;
surname: string;
age: number
}


Partial<T>
Делает все ключи необязательными
type PartialPerson = Partial<Person>

// то же самое, что
type PartialPerson = {
name?: string;
surname?: string;
age?: number
}


Required<T>
Обратное действие Partial — делает все ключи обязательными
Required<Partial<Person>> === Person


Readonly<Type>
Запрещает изменять поля объекта
const person: Readonly<Person> = {
name: "Denis",
surname: "Putnov",
age: 22
}

// ошибка, так как
// person нельзя изменять,
// только считывать (readonly)
person.name = 'Денис'


Record<Keys, Values>
Создаёт тип из ключей и значений, указанных отдельно
// ключи могут быть только строкой
// значения - только числом
type WordCounter = Record<string, number>

type Status = 'success' | 'error'
type StatusCounter = Record<Status, number>

// то же самое, что и Record ранее
type StatusCounter = {
success: number
error: number
}


Pick<Type, Keys>
Выбирает только нужные ключи из типа и возвращает новый тип
// из типа Person выбираем только свойства
// name и surname
type PersonName = Pick<Person, 'name' | 'surname'>

// то же самое
type PersonName = {
name: string
surname: string
}


Omit<Type, Keys>
Удаляет ненужные свойства из типа и возвращает новый тип
// Из типа Person исключаем свойство 'age'
type PersonName = Omit<Person, 'age'>;

// то же самое
type PersonName = {
name: string
surname: string
}


Parameters<Function>
Возвращает тип параметров функции
type Foo = (a: number, b: number) => string
type Params = Parameters<Foo>

Params // [a: number, b: number]


ReturnType<Function>
Возвращает тип возвращаемого параметра из функции
type Foo = (a: number, b: number) => string
type Return = ReturnType<Foo>

Return // string


Спасибо за прочтение, это важно для меня ❤️

@prog_way_blogчат — #theory #typescript #useful
🔥408👍5🐳4



tgoop.com/prog_way_blog/264
Create:
Last Update:

Шпаргалка по Utility-типам в TypeScript

В этом посте разберу только самые часто используемые, посмотреть все utility-типы можно в официальной документации.

type Person = {
name: string;
surname: string;
age: number
}


Partial<T>
Делает все ключи необязательными
type PartialPerson = Partial<Person>

// то же самое, что
type PartialPerson = {
name?: string;
surname?: string;
age?: number
}


Required<T>
Обратное действие Partial — делает все ключи обязательными
Required<Partial<Person>> === Person


Readonly<Type>
Запрещает изменять поля объекта
const person: Readonly<Person> = {
name: "Denis",
surname: "Putnov",
age: 22
}

// ошибка, так как
// person нельзя изменять,
// только считывать (readonly)
person.name = 'Денис'


Record<Keys, Values>
Создаёт тип из ключей и значений, указанных отдельно
// ключи могут быть только строкой
// значения - только числом
type WordCounter = Record<string, number>

type Status = 'success' | 'error'
type StatusCounter = Record<Status, number>

// то же самое, что и Record ранее
type StatusCounter = {
success: number
error: number
}


Pick<Type, Keys>
Выбирает только нужные ключи из типа и возвращает новый тип
// из типа Person выбираем только свойства
// name и surname
type PersonName = Pick<Person, 'name' | 'surname'>

// то же самое
type PersonName = {
name: string
surname: string
}


Omit<Type, Keys>
Удаляет ненужные свойства из типа и возвращает новый тип
// Из типа Person исключаем свойство 'age'
type PersonName = Omit<Person, 'age'>;

// то же самое
type PersonName = {
name: string
surname: string
}


Parameters<Function>
Возвращает тип параметров функции
type Foo = (a: number, b: number) => string
type Params = Parameters<Foo>

Params // [a: number, b: number]


ReturnType<Function>
Возвращает тип возвращаемого параметра из функции
type Foo = (a: number, b: number) => string
type Return = ReturnType<Foo>

Return // string


Спасибо за прочтение, это важно для меня ❤️

@prog_way_blogчат — #theory #typescript #useful

BY progway — программирование, IT


Share with your friend now:
tgoop.com/prog_way_blog/264

View MORE
Open in Telegram


Telegram News

Date: |

How to Create a Private or Public Channel on Telegram? More>> Telegram offers a powerful toolset that allows businesses to create and manage channels, groups, and bots to broadcast messages, engage in conversations, and offer reliable customer support via bots. Hui said the time period and nature of some offences “overlapped” and thus their prison terms could be served concurrently. The judge ordered Ng to be jailed for a total of six years and six months. A Hong Kong protester with a petrol bomb. File photo: Dylan Hollingsworth/HKFP.
from us


Telegram progway — программирование, IT
FROM American