- Регистрация
- 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
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,
Key Differences
| Feature | as | satisfies |
|---|---|---|
| Type checking | Not enforced | Enforced |
| Keeps extra properties | No | ![]() |
| Narrows const types | No | ![]() |
| Safer for configuration objects | No | ![]() |
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,
