Discover essential TypeScript coding best practices that help prevent subtle bugs and make your codebase robust, maintainable, and readable. Learn strategies that go beyond the basics for writing cleaner TypeScript in everyday frontend development.
Why is it generally considered better practice to use the 'unknown' type instead of 'any' in TypeScript functions that handle external input?
Explanation: Using 'unknown' forces explicit type-checking before using the value, making the code safer and less prone to runtime errors. 'unknown' does not automatically narrow types; type checks must be performed. 'any' sacrifices type safety for flexibility, not performance. 'unknown' values cannot be used as any type automatically; attempts to do so cause compiler errors until type-checked.
When is it more appropriate to use a union of string literals instead of an enum in TypeScript?
Explanation: A union of string literals is well-suited for cases requiring just a set of named string values, with no methods or runtime behaviors attached. Attaching methods is not available for union types. Numeric indexing and runtime extension are features more relevant to enums or classes, not basic union types.
How should you indicate that a function parameter is optional in TypeScript for the best type clarity?
Explanation: A question mark is the standard way to indicate that a parameter is optional in TypeScript, making the intent clear and readable. Using 'string | undefined' is possible but less concise and may not convey intent as clearly. Omitting the parameter would make it required. Using 'any' sacrifices type safety and clarity.
If you receive an unknown value and need to access a specific property safely, what is the best practice to ensure type safety in TypeScript?
Explanation: Type guards let you check the shape or type at runtime, ensuring safety before property access. Direct type assertions bypass safety checks, risking runtime errors. Assuming the value structure without checks can result in crashes. Casting to 'any' hides issues and disables compile-time safety.
Why is it advisable to avoid explicit type annotations when TypeScript can infer the type from initialization?
Explanation: When TypeScript can infer the type, explicit annotations do not improve safety and just add unnecessary noise. TypeScript's inference works well in many cases. Annotations have no impact on JavaScript runtime performance. Omitting a type does not make functions inaccessible.