Type Assertions, Debugging, and tsconfig
Type Assertions
Section titled “Type Assertions”A type assertion tells TypeScript, “Trust me, I know this value’s type.”
const input = document.getElementById("search") as HTMLInputElement;input.value = "TypeScript";Important:
- Assertions affect compile-time checks.
- They do not change runtime behavior.
Safer Alternative: Narrowing Instead of Asserting
Section titled “Safer Alternative: Narrowing Instead of Asserting”const element = document.getElementById("search");
if (element instanceof HTMLInputElement) { element.value = "safe";}Common TypeScript Errors
Section titled “Common TypeScript Errors”-
Implicit
anyExample: parameter without type under strict mode. -
nullandundefinedmismatch Happens when value might be missing but type says it cannot. -
Union misuse Accessing property without narrowing first.
-
Incomplete switch handling Forgetting one variant in discriminated unions.
Debugging Flow
Section titled “Debugging Flow”
graph TD
A[TypeScript Error] --> B[Read Full Message]
B --> C[Find Actual Type]
C --> D[Compare With Expected Type]
D --> E[Fix by Narrowing, Annotation, or Refactor]
Practical tsconfig for Learning and Interviews
Section titled “Practical tsconfig for Learning and Interviews”{ "compilerOptions": { "strict": true, "noImplicitAny": true, "strictNullChecks": true, "noUncheckedIndexedAccess": true, "exactOptionalPropertyTypes": true, "target": "ES2020", "module": "ESNext" }}These options force clean thinking and reduce hidden bugs.
Compile-Time Safety vs Runtime Safety
Section titled “Compile-Time Safety vs Runtime Safety”TypeScript checks type contracts before execution.
Use runtime checks for API data, user input, and external systems because TypeScript types are erased after compilation.