Telegram Group & Telegram Channel
📌 5 крутых фич TypeScript, о которых ты мог не знать

TypeScript — это не просто строгая типизация, но и мощный инструмент, который может сделать твой код чище и безопаснее. Сегодня покажу 5 полезных возможностей, которые ты мог упустить!

1️⃣ satisfies — Гарантия соответствия
Часто бывает, что мы определяем объект с определёнными ключами, но хотим, чтобы TypeScript проверил, соответствуют ли они ожидаемой схеме. Вот где пригодится satisfies:


type Theme = "light" | "dark";

const config = {
theme: "light",
debug: true,
} satisfies { theme: Theme; debug: boolean };

// Теперь TypeScript гарантирует, что `theme` всегда будет соответствовать "light" | "dark"


2️⃣ keyof + typeof — Безопасные ключи
Если у тебя есть объект и ты хочешь работать с его ключами безопасно, эта комбинация спасает:


const user = {
name: "Jhon",
age: 30,
};

type UserKeys = keyof typeof user; // "name" | "age"

const key: UserKeys = "name"; // TypeScript гарантирует, что это корректный ключ


3️⃣ Extract<> и Exclude<> — Фильтрация типов
Эти утилиты позволяют выделять или исключать типы из union-типов:


type EventType = "click" | "hover" | "scroll";
type MouseEvents = Extract<EventType, "click" | "hover">; // "click" | "hover"
type NonMouseEvents = Exclude<EventType, "click" | "hover">; // "scroll"


4️⃣ as const — Заморозка значений
Если тебе нужно, чтобы объект или массив стали неизменяемыми (и сохранили точные значения), используй as const:


const roles = ["admin", "user", "guest"] as const;

type Role = (typeof roles)[number]; // "admin" | "user" | "guest"


5️⃣ ReturnType<> — Получение типа возвращаемого значения
Если у тебя есть функция, и тебе нужно определить её возвращаемый тип, ReturnType<> сделает это за тебя:


function getUser() {
return { name: "Jhon", age: 30 };
}

type User = ReturnType<typeof getUser>; // { name: string; age: number }



✍️ @React_lib



tg-me.com/React_lib/660
Create:
Last Update:

📌 5 крутых фич TypeScript, о которых ты мог не знать

TypeScript — это не просто строгая типизация, но и мощный инструмент, который может сделать твой код чище и безопаснее. Сегодня покажу 5 полезных возможностей, которые ты мог упустить!

1️⃣ satisfies — Гарантия соответствия
Часто бывает, что мы определяем объект с определёнными ключами, но хотим, чтобы TypeScript проверил, соответствуют ли они ожидаемой схеме. Вот где пригодится satisfies:


type Theme = "light" | "dark";

const config = {
theme: "light",
debug: true,
} satisfies { theme: Theme; debug: boolean };

// Теперь TypeScript гарантирует, что `theme` всегда будет соответствовать "light" | "dark"


2️⃣ keyof + typeof — Безопасные ключи
Если у тебя есть объект и ты хочешь работать с его ключами безопасно, эта комбинация спасает:


const user = {
name: "Jhon",
age: 30,
};

type UserKeys = keyof typeof user; // "name" | "age"

const key: UserKeys = "name"; // TypeScript гарантирует, что это корректный ключ


3️⃣ Extract<> и Exclude<> — Фильтрация типов
Эти утилиты позволяют выделять или исключать типы из union-типов:


type EventType = "click" | "hover" | "scroll";
type MouseEvents = Extract<EventType, "click" | "hover">; // "click" | "hover"
type NonMouseEvents = Exclude<EventType, "click" | "hover">; // "scroll"


4️⃣ as const — Заморозка значений
Если тебе нужно, чтобы объект или массив стали неизменяемыми (и сохранили точные значения), используй as const:


const roles = ["admin", "user", "guest"] as const;

type Role = (typeof roles)[number]; // "admin" | "user" | "guest"


5️⃣ ReturnType<> — Получение типа возвращаемого значения
Если у тебя есть функция, и тебе нужно определить её возвращаемый тип, ReturnType<> сделает это за тебя:


function getUser() {
return { name: "Jhon", age: 30 };
}

type User = ReturnType<typeof getUser>; // { name: string; age: number }



✍️ @React_lib

BY React


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/React_lib/660

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Tata Power whose core business is to generate, transmit and distribute electricity has made no money to investors in the last one decade. That is a big blunder considering it is one of the largest power generation companies in the country. One of the reasons is the company's huge debt levels which stood at ₹43,559 crore at the end of March 2021 compared to the company’s market capitalisation of ₹44,447 crore.

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

telegram from in


Telegram React
FROM USA