Typescript TS
From satisfies INSTEAD-OF as
Go to text →
In most cases: Use keyword satisfies
instead of as
Why
The as
keyword is a type assertion that bypasses TypeScript's type checking - it tells the compiler "don't worry about it, hold my beer, I know what am doing". This can easily hide type errors.
In other words as
allows you to LIE to yourself at compile stage. Stating something fits the type when it does not.
The satisfies
operator (TypeScript 4.9+) validates that a value conforms to a type while preserving its narrower literal type. It provides compile-time safety without type widening.
Example
// ❌ Bad - missing fields will NOT cause errors at compile time
// ❌ Will cause issues at runtime
const config = {
name: "test",
// missing required 'age' field
} as { name: string; age: number };
// ✅ Good - TypeScript will error on missing fields
const config = {
name: "test",
// TypeScript error: Property 'age' is missing
} satisfies { name: string; age: number };
Nested as
Bypasses Outer satisfies
Even when using satisfies
at the top level, internal as
assertions can still bypass validation:
type Item = { id: number; name: string; required: boolean };
type Config = { itemA: Item; itemB: Item };
// ❌ Bad - internal 'as' bypasses validation even with outer 'satisfies'
const config = {
itemA: {
id: 1,
name: "A"
// missing 'required' field - NO ERROR!
} as Item, // 'as' lies about the type
} satisfies Config; // outer 'satisfies' can't catch the lie
// ✅ Good - remove all 'as' assertions for full validation
const config = {
itemA: {
id: 1,
name: "A"
// TypeScript error: Property 'required' is missing
}
} satisfies Config; // now TypeScript catches the error
Benefits
- Catches missing properties at compile time
- Preserves literal types and const assertions
- Provides better IntelliSense and type inference
- Makes refactoring safer
Children