TypeScript Anti-Patterns Overview
TypeScript Anti-Patterns Overview
Overusing any Type
Overusing any Type
any
defeats the purpose of TypeScript’s type system. It bypasses type checking and can lead to runtime errors that TypeScript is designed to prevent.Type Assertions Without Verification
Type Assertions Without Verification
as
keyword) tell the compiler to trust you without verification. Use type guards to validate data at runtime.Not Using readonly for Immutable Properties
Not Using readonly for Immutable Properties
readonly
modifier for properties that shouldn’t change after initialization to prevent accidental mutations.Using Object as a Type
Using Object as a Type
Object
type is too general and doesn’t provide useful type information. Use more specific types or generics.Not Leveraging Discriminated Unions
Not Leveraging Discriminated Unions
Using Function Types Instead of Interfaces
Using Function Types Instead of Interfaces
Not Using Strict Null Checks
Not Using Strict Null Checks
strictNullChecks
in your TypeScript configuration to catch null and undefined errors at compile time.Using String Enums Instead of Literal Types
Using String Enums Instead of Literal Types
Not Using Index Signatures Properly
Not Using Index Signatures Properly
Not Using Utility Types
Not Using Utility Types
Partial
, Readonly
, Pick
, Omit
, etc. Use them instead of manually creating derived types.Using namespace Instead of ES Modules
Using namespace Instead of ES Modules
Not Using Type Guards
Not Using Type Guards
typeof
, instanceof
, or custom predicates) to narrow types safely instead of type assertions.Not Using Interfaces for Public APIs
Not Using Interfaces for Public APIs
Using the Non-null Assertion Operator (!.)
Using the Non-null Assertion Operator (!.)
!
) tells TypeScript to ignore the possibility of null
or undefined
. This can lead to runtime errors if the value is actually null.Not Using Unknown for API Responses
Not Using Unknown for API Responses
unknown
instead of any
for values from external sources like API responses, then use type guards to narrow the type safely.Not Using Branded Types for IDs
Not Using Branded Types for IDs
Not Using Exhaustiveness Checking
Not Using Exhaustiveness Checking
Not Using Proper Module Augmentation
Not Using Proper Module Augmentation
Not Using Conditional Types
Not Using Conditional Types