You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: website/src/pages/index.mdx
+45-3Lines changed: 45 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -275,6 +275,48 @@ const iconColor: Color = 'blue-400';
275
275
const customColor:Color='#AD3128';
276
276
```
277
277
278
+
### Type-Safe Constants with `satisfies`
279
+
280
+
The `as const satisfies` syntax is a powerful feature in TypeScript that combines strict type-checking and immutability for constants. It is particularly useful when defining constants that need to conform to a specific type.
281
+
282
+
Key benefits:
283
+
284
+
- Immutability with `as const`
285
+
- Ensures the constant is treated as readonly.
286
+
- Narrows the types of values to their literals, preventing accidental modifications.
287
+
- Validation with `satisfies`
288
+
- Ensures the object conforms to a broader type without widening its inferred type.
289
+
- Helps catch type mismatches at compile time while preserving narrowed inferred types.
290
+
291
+
```ts
292
+
typeOrderStatus= {
293
+
pending:'pending'|'idle';
294
+
fulfilled:boolean;
295
+
error:string;
296
+
};
297
+
298
+
// ❌ Avoid mutable constant of wide type
299
+
const IDLE_ORDER:OrderStatus= {
300
+
pending: 'idle',
301
+
fulfilled: true,
302
+
error: 'Shipping Error',
303
+
};
304
+
305
+
// ❌ Avoid constant with incorrect values
306
+
const IDLE_ORDER = {
307
+
pending: 'done',
308
+
fulfilled: 'partially',
309
+
error: 116,
310
+
} asconst;
311
+
312
+
// ✅ Use immutable constant of narrowed type
313
+
const IDLE_ORDER = {
314
+
pending: 'idle',
315
+
fulfilled: true,
316
+
error: 'Shipping Error',
317
+
} asconstsatisfiesOrderStatus;
318
+
```
319
+
278
320
### Type any & unknown
279
321
280
322
`any` data type must not be used as it represents literally “any” value that TypeScript defaults to and skips type checking since it cannot infer the type. As such, `any` is dangerous, it can mask severe programming errors.
@@ -680,17 +722,17 @@ While it's often hard to find the best name, try optimize code for consistency a
680
722
} asconst;
681
723
```
682
724
683
-
If object type exist use `satisfies` operator in conjunction with const assertion, to conform object matches its type.
725
+
If type exist use `satisfies` operator in conjunction with const assertion, to conform object matches its type.
684
726
685
727
```ts
686
-
// OrderStatus type is already defined - e.g. generated from database schema model, API etc.
728
+
// OrderStatus is predefined (e.g. generated from database schema, API)
0 commit comments