• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Understanding TypeScript's `satisfies` vs `as`

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
In TypeScript, the satisfies operator is a safer, more precise alternative to as when you want to ensure a value conforms to a type without losing type inference.

Key Differences

Featureassatisfies
Type checkingNot enforcedEnforced
Keeps extra propertiesNoYes
Narrows const typesNoYes
Safer for configuration objectsNoYes
1. Keeping Extra Properties

Using as (unsafe):


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

const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
} as Person; // No error, but `email` is lost from the type
Using satisfies (safe):


const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
} satisfies Person;
// TS checks that name and age exist and retains `email` in the inferred type
2. Narrowing const Types

Using as:


const colors = ['red', 'green', 'blue'] as string[];
Using satisfies:


const colors = ['red', 'green', 'blue'] satisfies readonly ['red', 'green', 'blue'];
3. Ensuring Correct Object Shape

Using as (can lie):


type Config = { port: number };

const config = {
port: '3000',
} as Config; // No error, even though it's wrong!
Using satisfies (type checked):


const config = {
port: '3000',
} satisfies Config; // Type error: 'string' is not assignable to 'number'
4. With Utility Types


type Route = {
path: string;
name: string;
};

const routes = {
home: { path: '/', name: 'Home' },
about: { path: '/about', name: 'About' },
} satisfies Record<string, Route>;
Conclusion


Use satisfies when you want strong type validation without losing inferred details. It's ideal for configuration objects, constant arrays,


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу