File tree Expand file tree Collapse file tree 1 file changed +16
-9
lines changed Expand file tree Collapse file tree 1 file changed +16
-9
lines changed Original file line number Diff line number Diff line change @@ -637,28 +637,35 @@ Consider the advantages of explicitly defining the return type of a function::
637637
638638Strive declaring constants using const assertion ` as const ` :
639639
640- - type is narrowed
641- - object gets ` readonly ` properties
642- - array becomes ` readonly ` tuple
640+ - Type Narrowing - Using as const narrows the type of literals to their exact values rather than general types.
641+ - Immutability - Objects and arrays get readonly properties, preventing accidental mutations.
643642
644643 ` ` ` ts
645644 // ❌ Avoid
646645 const FOO_LOCATION = { x: 50 , y: 130 }; // Type { x: number; y: number; }
647646 FOO_LOCATION .x = 10 ;
648647
649- const BAR_LOCATION = [50 , 130 ]; // Type number[]
650- BAR_LOCATION .push (10 );
651-
652- const RATE_LIMIT = 25 ;
653- const RATE_LIMIT_MESSAGE = ` Max number of requests/min is ${RATE_LIMIT }. ` ; // Type string
654-
655648 // ✅ Use
656649 const FOO_LOCATION = { x: 50 , y: 130 } as const ; // Type '{ readonly x: 50; readonly y: 130; }'
657650 FOO_LOCATION .x = 10 ; // Error
651+ ` ` `
652+
653+ ` ` ` ts
654+ // ❌ Avoid
655+ const BAR_LOCATION = [50 , 130 ]; // Type number[]
656+ BAR_LOCATION .push (10 );
658657
658+ // ✅ Use
659659 const BAR_LOCATION = [50 , 130 ] as const ; // Type 'readonly [10, 20]'
660660 BAR_LOCATION .push (10 ); // Error
661+ ` ` `
662+
663+ ` ` ` ts
664+ // ❌ Avoid
665+ const RATE_LIMIT = 25 ;
666+ const RATE_LIMIT_MESSAGE = ` Max number of requests/min is ${RATE_LIMIT }. ` ; // Type string
661667
668+ // ✅ Use
662669 const RATE_LIMIT = 25 ;
663670 const RATE_LIMIT_MESSAGE = ` Max number of requests/min is ${RATE_LIMIT }. ` as const ; // Type 'Rate limit exceeded! Max number of requests/min is 25.'
664671 ` ` `
You can’t perform that action at this time.
0 commit comments